How to get a “hashed device id” for testing admob

2019-01-23 05:44发布

When implementing AdMob you can define an array of test IDs so that Google knows to serve test ads to these devices, instead of real ads. However, it requires "hashed device IDs". This seems a little vague to me. What ID are they talking about and what hashing method do they expect me to use?

I'm talking about the bit that should go in here:

request.testDevices = @[ @"hashed-device-id" ];

7条回答
混吃等死
2楼-- · 2019-01-23 06:32

For some reason I was not seeing the "To get test ads..." in the Console. In any case, you might want your beta testers to not have to delve into the darkness to find this and send it to you to hard-code. Here is Felix's (correct, thankyouverymuch) answer in Swift 3 version, using code from http://iosdeveloperzone.com/2014/10/03/using-commoncrypto-in-swift/

Note that you will have to have a bridging header with the following:

#import <CommonCrypto/CommonCrypto.h>

Here's the hash function:

func md5(_ string: String) -> String {
    let context = UnsafeMutablePointer<CC_MD5_CTX>.allocate(capacity: 1)
    var digest = Array<UInt8>(repeating:0, count:Int(CC_MD5_DIGEST_LENGTH))
    CC_MD5_Init(context)
    CC_MD5_Update(context, string, CC_LONG(string.lengthOfBytes(using: String.Encoding.utf8)))
    CC_MD5_Final(&digest, context)
    context.deallocate(capacity: 1)
    var hexString = ""
    for byte in digest {
       hexString += String(format:"%02x", byte)
    }
    return hexString
}

And here it is put to use in Google's sample code:

func createAndLoadInterstitial() {
    interstitial = GADInterstitial(adUnitID: G.googleMobileTestAdsId)
    interstitial.delegate = self
    let request = GADRequest()

    // Here's the magic.
    let id = ASIdentifierManager.shared().advertisingIdentifier!
    let md5id = md5(id.uuidString)

    // And now we use the magic.
    request.testDevices = [ kGADSimulatorID, md5id ]
    interstitial.load(request)
}
查看更多
登录 后发表回答