刚刚发现,UIDevice uniqueIdentifier属性在iOS 5中已弃用,在iOS 7及以上版本中不可用。似乎没有可供选择的方法或属性。

我们现有的许多应用程序都紧密依赖于这个属性来唯一地识别特定的设备。今后我们该如何处理这个问题?

2011-2012年的文件建议:

特殊注意事项 不要使用uniqueIdentifier属性。创建特定的唯一标识符 你可以调用CFUUIDCreate函数来创建一个UUID,然后写入 使用NSUserDefaults类将它转换到默认数据库。

但是,如果用户卸载和重新安装应用程序,这个值就不一样了。


当前回答

你可以通过以下代码实现:uidevice -with- uniqueidentifier -for ios -5

其他回答

从ios6开始,我们有了NSUUID类,它符合RFC4122

Apple Link: apple_ref for NSUUID

你可以通过以下代码实现:uidevice -with- uniqueidentifier -for ios -5

虽然不完美,但却是UDID的最佳和最接近的替代品之一(在Swift中使用iOS 8.1和Xcode 6.1):

生成一个随机UUID

let strUUID: String = NSUUID().UUIDString

并使用KeychainWrapper库:

给keychain添加一个字符串值:

let saveSuccessful: Bool = KeychainWrapper.setString("Some String", forKey: "myKey")

从keychain中检索字符串值:

let retrievedString: String? = KeychainWrapper.stringForKey("myKey")

从keychain中删除一个字符串值:

let removeSuccessful: Bool = KeychainWrapper.removeObjectForKey("myKey")

该解决方案使用了keychain,因此存储在keychain中的记录将被持久化,即使在应用程序卸载和重新安装之后。删除该记录的唯一方法是重置设备的所有内容和设置。这就是为什么我提到这个替代方案并不完美,但仍然是iOS 8.1上使用Swift替代UDID的最佳方案之一。

我们可以在ios7中使用identifierForVendor,

-(NSString*)uniqueIDForDevice
{
    NSString* uniqueIdentifier = nil;
    if( [UIDevice instancesRespondToSelector:@selector(identifierForVendor)] ) { // >=iOS 7
        uniqueIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    } else { //<=iOS6, Use UDID of Device       
            CFUUIDRef uuid = CFUUIDCreate(NULL);
            //uniqueIdentifier = ( NSString*)CFUUIDCreateString(NULL, uuid);- for non- ARC
            uniqueIdentifier = ( NSString*)CFBridgingRelease(CFUUIDCreateString(NULL, uuid));// for ARC
            CFRelease(uuid);
         }
    }
return uniqueIdentifier;
}

——重要提示——

UDID和identifierForVendor是不同的:——

1.) On uninstalling  and reinstalling the app identifierForVendor will change.

2.) The value of identifierForVendor remains the same for all the apps installed from the same vendor on the device.

3.) The value of identifierForVendor also changes for all the apps if any of the app (from same vendor) is reinstalled.

看看这个,

我们可以使用Keychain来代替NSUserDefaults类,来存储CFUUIDCreate创建的UUID。

这样我们就可以避免重新安装UUID, 即使用户卸载并重新安装,也始终为同一应用程序获得相同的UUID。

用户重置设备时将重新创建UUID。

我用SFHFKeychainUtils尝试了这种方法,它的工作就像一个魅力。