I'd like to save at most one record (i.e. a rating) per user in a table of the public database. For this I need to save the current user ID or device ID. But how can I get it?
5 Answers
Get iCloud ID / CloudKit Record ID with Swift 2
Here is a snippet which I am always using to fetch the iPhone user’s iCloud ID (Apple calls it CloudKit Record ID) for an iOS app.
The only thing you need to do in Xcode is to activate the "CloudKit" checkbox in your project’s iCloud capabilities. You do not need to actively use CloudKit at all - it is just the core of all iCloud activities since iOS 8.
It is important to know that Apple never directly exposes the real iCloud ID but always just returns a secured hash of the iCloud ID and your app ID. But that should not worry you because that string is still unique for each user of your app across all his devices and can be used as login replacement.
My function, is async and returns an optional CKRecordID object. The most interesting property of that CKRecordID object is recordName.
CKRecordID.recordName
is a 33 character string where the first character is always an underscore followed by 32 unique characters (== your user iCloud ID encoded for your app). It looks similar to: "_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")
}
}
-
I get an exception when I do CKContainer.defaultContainer() libc++abi.dylib: terminating with uncaught exception of type CKException Commented Mar 9, 2018 at 9:50
-
1@Sebastian Can i use this recordID to uniquely identify a user with same icloud account at different devices? I mean if a user installs app and write some notes. Then i save those notes on firebase. And then that user installs the app at another device with same icloud account, can i retrieve the notes already written with another device? Commented May 13, 2018 at 18:52
-
2@SalmanAli Yes and that is one of the most important aspects of it. I wrote a blog post about it some years ago: medium.com/@skreutzb/… Commented May 14, 2018 at 6:41
-
@Sebastian some times the recordName returned is nil and signing out and signing in again to icloud solves the problem but Is there any cause or a better programmatical solution for this issue Commented Jul 18, 2018 at 13:53
You'll want to call -[CKContainer fetchUserRecordIDWithCompletionHandler:]
to fetch the current user record ID:
-
I get an exception when I do CKContainer.defaultContainer() libc++abi.dylib: terminating with uncaught exception of type CKException Commented Mar 9, 2018 at 9:50
Here is the code snippet for 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")
}
}
-
i got error like, Terminating app due to uncaught exception 'CKException', reason: 'The application is missing required entitlement com.apple.developer.icloud-services' Commented Nov 25, 2017 at 9:32
-
-
-
@Yi-HsiuLee Can i use this recordID to uniquely identify a user with same icloud account at different devices? I mean if a user installs app and write some notes. Then i save those notes on firebase. And then that user installs the app at another device with same icloud account, can i retrieve the notes already written with another device? Commented May 13, 2018 at 18:53
Here's the async alternative:
let userRecord = try await CKContainer.default().userRecordID()
A more compact Swift 5 code solution:
CKContainer.default().fetchUserRecordID(completionHandler: { (recordId, error) in
if let name = recordId?.recordName {
print("iCloud ID: " + name)
}
else if let error = error {
print(error.localizedDescription)
}
})
For a specific CloudKit container, use this code:
CKContainer(identifier: "<Your CloudKit container identifier>").fetchUserRecordID(completionHandler: { (recordId, error) in
if let name = recordId?.recordName {
print("iCloud ID: " + name)
}
else if let error = error {
print(error.localizedDescription)
}
})
-
1For some reason this returns an error for me: "Couldn't get container configuration from the server for container "iCloud.com.my_container_name". Any idea why? I have user records in the Users record type showing in Cloudkit Dashboard– mumushCommented Nov 14, 2020 at 3:06