引言
由于项目中之前一直采用 IDFA 作为应用的唯一标识,而在 iOS 10 之后,如果用户手动限制广告跟踪的话(设置-隐私-广告-限制广告跟踪),IDFA 返回的将全是零。
iOS 之前用户限制广告跟踪的话只是重置 IDFA。
正文
于是想到将 IDFA 存储到钥匙串中。
iOS 设备唯一标识逻辑.png
#import <AdSupport/AdSupport.h>
#import "SFHFKeychainUtils.h"
static NSString * const kDeviceIdentifier = @"kDeviceIdentifier";
- (NSString *)getDeviceIdentifier {
//从钥匙串中获取唯一设备标识
NSString * deviceIdentifier = [SFHFKeychainUtils getPasswordForUsername:kDeviceIdentifier andServiceName:[[NSBundle mainBundle] bundleIdentifier] error:nil];
if (deviceIdentifier) {
//如果钥匙串中存在唯一标识,则直接返回
return deviceIdentifier;
}
//获取IDFA
NSString *IDFA = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
//判断IDFA是否为空
BOOL isEmpty = [[IDFA stringByReplacingOccurrencesOfString:@"-" withString:@""] stringByReplacingOccurrencesOfString:@"0" withString:@""].length;
if (isEmpty) {
//不为空,将IDFA作为唯一标识
deviceIdentifier = IDFA;
}
else {
//为空,获取UUID作为唯一标识
deviceIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
}
//保存唯一设备标识,如已存在则不进行任何处理
[SFHFKeychainUtils storeUsername:kDeviceIdentifier andPassword:deviceIdentifier forServiceName:[[NSBundle mainBundle]bundleIdentifier] updateExisting:NO error:nil];
//返回唯一标识
return deviceIdentifier;
}```
代码中使用封装类 SFHFKeychainUtils 在 keychain 中存取 IDFA 。
参考文章:
http://www.jianshu.com/p/5e31e0699035
https://github.com/ldandersen/scifihifi-iphone/tree/master/security