Skip to content

Instantly share code, notes, and snippets.

@saito-sv
Forked from bizz84/ICloudUserIDProvider.swift
Created March 23, 2019 06:34
Show Gist options
  • Save saito-sv/3064c62aaaa45b8f080596b5c9e86eab to your computer and use it in GitHub Desktop.
Save saito-sv/3064c62aaaa45b8f080596b5c9e86eab 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