-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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