我想在公共数据库的表中保存每个用户最多一条记录(即评级).为此,我需要保存当前用户ID或设备ID.但我怎么能得到它?
Seb*_*ian 29
这是一个片段,我一直用它来获取iPhone应用程序的iPhone用户的iCloud ID(Apple称之为CloudKit Record ID).
您在Xcode中唯一需要做的就是在项目的iCloud功能中激活"CloudKit"复选框.您根本不需要主动使用CloudKit - 它只是iOS 8以来所有iCloud活动的核心.
重要的是要知道Apple永远不会直接暴露真实的iCloud ID,但总是只返回iCloud ID和您的应用ID的安全散列.但这不应该让您担心,因为该字符串对于您的应用程序中的每个用户而言仍然是唯一的,并且可以用作登录替换.
我的函数是异步并返回一个可选的CKRecordID对象.该CKRecordID对象最有趣的属性是recordName.
CKRecordID.recordName是一个33个字符的字符串,其中第一个字符始终是下划线,后跟32个唯一字符(==您的应用为您的用户编写的iCloud ID).它看起来类似于:"_cd2f38d1db30d2fe80df12c89f463a9e"
import CloudKit
/// async gets iCloud record name of logged-in user
func iCloudUserIDAsync(complete: (instance: CKRecordID?, error: NSError?) -> ()) {
let container = CKContainer.defaultContainer()
container.fetchUserRecordIDWithCompletionHandler() {
recordID, error in
if error != nil {
print(error!.localizedDescription)
complete(instance: nil, error: error)
} else {
print("fetched ID \(recordID?.recordName)")
complete(instance: recordID, error: nil)
}
}
}
// call the function above in the following way:
// (userID is the string you are intersted in!)
iCloudUserIDAsync() {
recordID, error in
if let userID = recordID?.recordName {
print("received iCloudID \(userID)")
} else {
print("Fetched iCloudID was nil")
}
}
Run Code Online (Sandbox Code Playgroud)
这是Swift 3的代码片段
import CloudKit
/// async gets iCloud record ID object of logged-in iCloud user
func iCloudUserIDAsync(complete: @escaping (_ instance: CKRecordID?, _ error: NSError?) -> ()) {
let container = CKContainer.default()
container.fetchUserRecordID() {
recordID, error in
if error != nil {
print(error!.localizedDescription)
complete(nil, error as NSError?)
} else {
print("fetched ID \(recordID?.recordName)")
complete(recordID, nil)
}
}
}
// call the function above in the following way:
// (userID is the string you are interested in!)
iCloudUserIDAsync { (recordID: CKRecordID?, error: NSError?) in
if let userID = recordID?.recordName {
print("received iCloudID \(userID)")
} else {
print("Fetched iCloudID was nil")
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10551 次 |
| 最近记录: |