其他分享
首页 > 其他分享> > iOS获取手机唯一标识

iOS获取手机唯一标识

作者:互联网

项目需求,在用户没有登录情况下根据手机标识作为身份认证获取对应信息。

NSString *UUID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];

系统提供了获取uuid的方法作为设备唯一标识,但是存在一个缺陷。
根据官方解释

The value of this property is the same for apps that come from the same vendor running on the same device. A different value is returned for apps on the same device that come from different vendors, and for apps on different devices regardless of vendor.
对于来自同一设备上运行的同一供应商的应用,此属性的值相同。 对于来自不同供应商的同一设备上的应用程序以及不同供应商的不同设备上的应用程序,将返回不同的值。

这保证了uuid的唯一性。

The value in this property remains the same while the app (or another app from the same vendor) is installed on the iOS device. The value changes when the user deletes all of that vendor’s apps from the device and subsequently reinstalls one or more of them.
在iOS设备上安装app(或来自同一供应商的其他应用程序)时,此属性中的值保持不变。 当用户从设备中删除所有该供应商的应用程序并随后重新安装其中一个或多个应用程序时,该值会更改。

这就导致了用户设备上只有我账号下的一款app,卸载重新安装后会得到不同的uuid,也就无法获取之前的数据了。
为了解决这个问题,我查找资料发现相关文章还不少,使用keychain可以解决这个问题。将第一次获取的uuid保存到keychain中,即使设备卸载了,再从keychain中获取uuid就可以保证统一性了。
我使用了GitHub上的一个SSKeychain(封装了系统的keychain操作)第三方库来处理的。

// 获取设备uuid
+ (NSString *)deviceUUID
{
    return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
}
// 保存uuid到keychain中
+ (void)saveUUID
{
    [SSKeychain setPassword:[self deviceUUID] forService:kService account:kAccount];
}
// 读取保存在keychain中的uuid
+ (NSString *)readUUID
{
    NSString *UUID = [SSKeychain passwordForService:kService account:kAccount];
    // 不存在则获取uuid保存到keychain中
    if (!UUID || UUID.length == 0) {
        [self saveUUID];
        UUID = [self deviceUUID];
    }
    return UUID;
}

按照文档介绍下载并将SSKeychain相关文件拖入项目即可使用
1、Add Security.framework to your target
2、Add SSKeychain.h, SSKeychain.m, SSKeychainQuery.h, and SSKeychainQuery.m to your project.
不要说看不懂上面英文啥意思,要打屁股的。
我把SSKeychain4个文件拖入项目运行有个报错,自行修改下就好,比较简单

SSKeychain GitHub链接
iOS Keychain使用

标签:keychain,uuid,获取,SSKeychain,iOS,same,标识,UUID
来源: https://blog.csdn.net/u011248221/article/details/88305929