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

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


当前回答

Swift 3。X最新工作代码,使用方便;

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

其他回答

我试过了

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

而不是

let UUID = NSUUID().UUIDString

这很有效。

class func uuid(completionHandler: @escaping (String) -> ()) {
    if let uuid = UIDevice.current.identifierForVendor?.uuidString {
        completionHandler(uuid)
    }
    else {
        // If the value is nil, wait and get the value again later. This happens, for example, after the device has been restarted but before the user has unlocked the device.
        // https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor?language=objc
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            uuid(completionHandler: completionHandler)
        }
    }
}

从iOS 11开始,你可以使用苹果的api: DeviceCheck

if (UIDevice.current.identifierForVendor?.uuidString) != nil
        {
            self.lblDeviceIdValue.text = UIDevice.current.identifierForVendor?.uuidString
        }

Swift 3。X最新工作代码,使用方便;

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