如何在Swift中获得唯一的设备ID?

如何在Swift中获得设备唯一ID?

我需要在数据库中使用ID,并在我的社交应用程序中作为我的Web服务的API密钥。 一些东西来跟踪这个设备的日常使用,并将其查询限制在数据库中。

谢谢!

你可以使用这个(Swift 3):

UIDevice.current.identifierForVendor!.uuidString 

对于旧版本:

 UIDevice.currentDevice().identifierForVendor 

或者如果你想要一个string:

 UIDevice.currentDevice().identifierForVendor!.UUIDString 

用户卸载应用程序后,不再有唯一标识设备的方法。 该文件说:

此应用程序(或来自同一供应商的另一个应用程序)安装在iOS设备上时,此属性中的值保持不变。 当用户从设备上删除所有供应商的应用程序并随后重新安装其中一个或多个应用程序时,该值会更改。

您可能还想阅读Mattt Thompson的这篇文章,了解更多细节:
http://nshipster.com/uuid-udid-unique-identifier/

对于Swift 3.X最新的工作代码,易于使用;

  let deviceID = UIDevice.current.identifierForVendor!.uuidString print(deviceID) 

您可以使用UIDevice类中的identifierForVendor公共属性

 let UUIDValue = UIDevice.currentDevice().identifierForVendor!.UUIDString print("UUID: \(UUIDValue)") 

编辑斯威夫特3:

 UIDevice.current.identifierForVendor!.uuidString 

结束编辑

属性层次结构的截图

您可以使用devicecheck (在Swift 4) Apple文档

 func sendEphemeralToken() { //check if DCDevice is available (iOS 11) //get the **ephemeral** token DCDevice.current.generateToken { (data, error) in guard let data = data else { return } //send **ephemeral** token to server to let token = data.base64EncodedString() //Alamofire.request("https://myServer/deviceToken" ... } } 

典型用法:

通常,您使用DeviceCheck API确保新用户尚未使用同一设备上的不同用户名称兑换优惠。

服务器操作需要:

参见WWDC 2017 – 会话702

更多来自Santosh Botre文章 – iOS设备的唯一标识符

您的关联服务器将此令牌与从Apple收到的validation密钥相结合,并使用结果请求访问每个设备的位。

Swift 2.2

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let userDefaults = NSUserDefaults.standardUserDefaults() if userDefaults.objectForKey("ApplicationIdentifier") == nil { let UUID = NSUUID().UUIDString userDefaults.setObject(UUID, forKey: "ApplicationIdentifier") userDefaults.synchronize() } return true } //Retrieve print(NSUserDefaults.standardUserDefaults().valueForKey("ApplicationIdentifier")!) 

我试过了

 let UUID = UIDevice.currentDevice().identifierForVendor?.UUIDString 

代替

 let UUID = NSUUID().UUIDString 

它的工作。