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

224

如何在Swift中获取设备的唯一标识符?

我需要一个ID用于数据库,并作为我的社交应用程序中Web服务的API密钥。这样可以跟踪该设备的每日使用情况并限制其对数据库的查询。

12个回答

-3
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)
        }
    }
}

-22

我已经尝试过

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

而不是

let UUID = NSUUID().UUIDString

它可以正常工作。


40
NSUUID().UUIDString每次都会生成一个新的字符串。 - Eric

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接