Skip to content

Instantly share code, notes, and snippets.

@bizz84
Created February 7, 2017 10:35
Show Gist options
  • Save bizz84/ebeb9a11f99d0bb70c7b7c598170add9 to your computer and use it in GitHub Desktop.
Save bizz84/ebeb9a11f99d0bb70c7b7c598170add9 to your computer and use it in GitHub Desktop.
Code to get iCloud unique user ID or prompt user to sign in to iCloud
import CloudKit
enum ICloudUserIDResponse {
case success(record: CKRecordID)
case failure(error: Error)
case notSignedIn(accountStatus: CKAccountStatus)
}
class ICloudUserIDProvider: NSObject {
class func getUserID(completion: @escaping (_ response: ICloudUserIDResponse) -> ()) {
let container = CKContainer.default()
container.accountStatus() { accountStatus, error in
if accountStatus == .available {
container.fetchUserRecordID() { recordID, error in
guard let recordID = recordID else {
let error = error ?? NSError(domain: "", code: 0, userInfo: nil)
completion(.failure(error: error))
return
}
completion(.success(record: recordID))
}
}
else {
completion(.notSignedIn(accountStatus: accountStatus))
}
}
}
}
func request() {
ICloudUserIDProvider.getUserID() { response in
switch response {
case .success(let record):
print("recordName: \(record.recordName)")
case .failure(let error):
print("error: \(error.localizedDescription)")
case .notSignedIn(_):
print("please sign in to iCloud")
if let settingsURL = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment