获取设备唯一标识符 (Device ID) 的 Swift 代码示例
获取设备唯一标识符 (Device ID) 的 Swift 代码示例
该代码示例演示了如何在 Swift 中使用 SAMKeychain 获取设备唯一标识符 (Device ID)。
static func getDeviceNumber() -> String {
var deviceNumber = SAMKeychain.password(forService: 'com.ColorSkin.app', account: 'app')
if deviceNumber?.count == 0 {
deviceNumber = UIDevice.current.identifierForVendor?.uuidString
deviceNumber = deviceNumber?.replacingOccurrences(of: '-', with: '')
SAMKeychain.setPassword(deviceNumber, forService: 'com.ColorSkin.app', account: 'app')
}
return deviceNumber ?? ''
}
代码解释:
getDeviceNumber()函数: 该函数用于获取设备唯一标识符。SAMKeychain.password(forService:account:): 从钥匙串中获取已存储的设备号。deviceNumber?.count == 0: 检查钥匙串中是否有已存储的设备号。如果没有,则继续获取新设备号。UIDevice.current.identifierForVendor?.uuidString: 获取设备的identifierForVendor并将其转换为 UUID 字符串。deviceNumber?.replacingOccurrences(of: '-', with: ''): 删除 UUID 字符串中的连字符。SAMKeychain.setPassword(_:forService:account:): 将新获取的设备号存储到钥匙串中。return deviceNumber ?? '': 返回获取的设备号,如果未获取到则返回空字符串。
注意:
identifierForVendor是一个唯一标识设备的标识符,但它可能在同一用户的所有设备上相同。- 该示例使用 SAMKeychain 来存储设备号,以确保设备号在应用重启后仍然可用。
- 使用
identifierForVendor时,请确保在你的应用隐私政策中清楚地说明你如何使用该标识符。
原文地址: https://www.cveoy.top/t/topic/qvzj 著作权归作者所有。请勿转载和采集!