【发布时间】:2014-11-13 13:12:41
【问题描述】:
如何在 Swift 中获取设备的唯一 ID?
我需要一个 ID 以在数据库中使用,并作为我的社交应用程序中的 Web 服务的 API 密钥。跟踪这些设备的日常使用情况并将其查询限制在数据库中。
【问题讨论】:
标签: ios swift uuid uniqueidentifier
如何在 Swift 中获取设备的唯一 ID?
我需要一个 ID 以在数据库中使用,并作为我的社交应用程序中的 Web 服务的 API 密钥。跟踪这些设备的日常使用情况并将其查询限制在数据库中。
【问题讨论】:
标签: ios swift uuid uniqueidentifier
你可以使用这个(Swift 3):
UIDevice.current.identifierForVendor!.uuidString
对于旧版本:
UIDevice.currentDevice().identifierForVendor
或者如果你想要一个字符串:
UIDevice.currentDevice().identifierForVendor!.UUIDString
用户卸载应用程序后,不再有唯一标识设备的方法。文档说:
当应用程序(或来自同一供应商的另一个应用程序)安装在 iOS 设备上时,此属性中的值保持不变。当用户从设备中删除该供应商的所有应用并随后重新安装其中一个或多个时,该值会发生变化。
您可能还想阅读 Mattt Thompson 的这篇文章以了解更多详情:
http://nshipster.com/uuid-udid-unique-identifier/
Swift 4.1 更新,您需要使用:
UIDevice.current.identifierForVendor?.uuidString
【讨论】:
您可以使用 devicecheck(在 Swift 4 中) Apple documentation
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 来确保新用户尚未在同一设备上以不同的用户名兑换优惠。
服务器操作需求:
See WWDC 2017 — Session 702 (24:06)
more from Santosh Botre article - Unique Identifier for the iOS Devices
您的关联服务器将此令牌与您从 Apple 收到的身份验证密钥相结合,并使用结果请求访问每个设备的位。
【讨论】:
generateToken 的数据令牌还不够吗?
适用于Swift 3.X最新工作代码,使用方便;
let deviceID = UIDevice.current.identifierForVendor!.uuidString
print(deviceID)
【讨论】:
【讨论】:
斯威夫特 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")!)
【讨论】:
if (UIDevice.current.identifierForVendor?.uuidString) != nil
{
self.lblDeviceIdValue.text = UIDevice.current.identifierForVendor?.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)
}
}
}
【讨论】:
我试过了
let UUID = UIDevice.currentDevice().identifierForVendor?.UUIDString
改为
let UUID = NSUUID().UUIDString
它有效。
【讨论】: