是一串由40位16进制数组成的字符串,用以标识唯一的设备,现在想通过代码获取是不可能的了,如果你想看看你设备的UDID,可以通过iTunes来查看。
缺点:
关于获取UDID代码:
[[UIDevice currentDevice] uniqueIdentifier];
缺点:
关于获取UUID的代码:
[[UIDevice currentDevice] identifierForVendor];
不过,设备唯一标示的问题仍然没有解决:如果你删除应用然后再次安装,这个identifierForVendor的值就变了。
思路:
关于获取UUID,这是官方API的建议方法:
- (NSString *) uniqueString
{
CFUUIDRef unique = CFUUIDCreate(kCFAllocatorDefault);
NSString *result = [(NSString *)CFUUIDCreateString(kCFAllocatorDefault, unique) autorelease];
CFRelease(unique);
return result;
}
如上获取的UUID,基于Git上的一个第三方库SSKeychain,可以将UUID保存在keychain里面,每次调用先检查钥匙串里面有没有,有则使用,没有则写进去,保证其唯一性,
参考代码:
- (NSString *)getNewUniqueIdNum{
NSString *uuidStr = [SSKeychain passwordForService:@"com.test.app1" account:@"user"];
if (!uuidStr || [uuidStr isEqualToString:@""])
{
CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
uuidStr = (__bridge NSString *)CFUUIDCreateString(kCFAllocatorDefault ,uuidRef);
[SSKeychain setPassword:[NSString stringWithFormat:@"%@", uuidStr] forService:@"com.test.app1"account:@"user"];
}
return uuidStr;
}
不同于上面调用的字符串转换(__bridge NSString *),另一种写法:
- (NSString *)getNewUniqueIdNum{
NSString *identifierNumber = [SSKeychain passwordForService:@"com.test.app1"account:@"user"];
CFUUIDRef uuidRef = CFUUIDCreate(NULL);
assert(uuidRef != NULL);
CFStringRef uuidStrRef = CFUUIDCreateString(NULL, uuidRef);
if (!identifierNumber){
[SSKeychain setPassword: [NSString stringWithFormat:@"%@", uuidStrRef] forService:@"com.test.app1"account:@"user"];
identifierNumber = [SSKeychain passwordForService:@"com.test.app1"account:@"user"];
}
return identifierNumber;
}
不同于如上SSKeychain,基于一个第三方库SAMKeyChains。SAMKeyChains对苹果安全框架API进行了简单封装,支持对存储在钥匙串中密码、账户进行访问,包括读取、删除和设置。SAMKeyChains使用简单,通过实例代码便可掌握。
基于SAMKeyChains方案的参考代码:
+ (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;
}
CFUUIDRef
CFStringRef
CFUUIDCreate
CFUUIDCreateString