获取iOS设备的唯一标识

来源:互联网 发布:sql developer导入dmp 编辑:程序博客网 时间:2024/05/17 04:43

考虑到之前苹果提供的各种方法随着系统版本的更新都被淘汰掉了,在网上找到了一种方法:利用keychain和UUID永久获得设备的唯一标识。

这里使用的一个第三方库,导入之后方便项目中使用 SAMKeyChains

//保存一个UUID字符串到钥匙串:CFUUIDRef uuid = CFUUIDCreate(NULL);assert(uuid != NULL);CFStringRef uuidStr = CFUUIDCreateString(NULL, uuid); [SAMKeychain setPassword: [NSString stringWithFormat:@"%@", uuidStr] forService:@"com.yourapp.yourcompany"account:@"user"];//从钥匙串读取UUID:NSString *retrieveuuid = [SAMKeychain passwordForService:@"com.yourapp.yourcompany"account:@"user"];**注意: setPassword和passwordForSevice方法中的**services 和 accounts 参数应该是一致的。

基本的实现思路便是这样,下面是具体的一种具体实现代码,仅供参考

+ (NSString *)getDeviceId{    NSString * currentDeviceUUIDStr = [SAMKeychain passwordForService:@" "account:@"uuid"];    if (currentDeviceUUIDStr == nil || [currentDeviceUUIDStr isEqualToString:@""])    {        NSUUID * currentDeviceUUID  = [UIDevice currentDevice].identifierForVendor;        currentDeviceUUIDStr = currentDeviceUUID.UUIDString;        currentDeviceUUIDStr = [currentDeviceUUIDStr stringByReplacingOccurrencesOfString:@"-" withString:@""];        currentDeviceUUIDStr = [currentDeviceUUIDStr lowercaseString];        [SAMKeychain setPassword: currentDeviceUUIDStr forService:@" "account:@"uuid"];    }    return currentDeviceUUIDStr;}