我想在公共数据库的表中保存每个用户最多一条记录(即评级)。为此,我需要保存当前用户ID或设备ID。但我怎么能得到它?
答案 0 :(得分:27)
这是一个片段,我一直用它来获取iPhone应用程序的iPhone用户的iCloud ID(Apple称之为CloudKit Record ID)。
在Xcode中你唯一需要做的就是激活" CloudKit"项目的iCloud功能中的复选框。您根本不需要主动使用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")
}
}
答案 1 :(得分:22)
您需要致电-[CKContainer fetchUserRecordIDWithCompletionHandler:]
以获取当前用户记录ID:
答案 2 :(得分:6)
以下是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")
}
}
答案 3 :(得分:2)
更紧凑的Swift 5代码解决方案:
CKContainer.default().fetchUserRecordID(completionHandler: { (recordId, error) in
if let name = recordId?.recordName {
print("iCloud ID: " + name)
}
else if let error = error {
print(error.localizedDescription)
}
})