Ludwig H. Ludwig H. - 2 months ago 15x
iOS Question

How to check if user is signed in into iCloud before saving data

Before saving data into CloudKit, how do I check that user has an account and is signed in?


You need to use accountStatusWithCompletionHandler from the CKContainer class and check the accountStatus returned.

This is described in the CloudKit Quick Start documentation.

Here is the Swift version of the example:

    CKContainer.defaultContainer().accountStatusWithCompletionHandler { accountStatus, error in
        if accountStatus == .NoAccount {
            let alert = UIAlertController(title: "Sign in to iCloud", message: "Sign in to your iCloud account to write records. On the Home screen, launch Settings, tap iCloud, and enter your Apple ID. Turn iCloud Drive on. If you don't have an iCloud account, tap Create a new Apple ID.", preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        } else {
            // Code if user has account here...