Episode #259

Hello Cloud Kit - Part 2

Series: Hello CloudKit

10 minutes
Published on March 9, 2017
In order to use CloudKit to read or write private data (or to write in the public database) the user will have to be signed in to iCloud on their device. If they are not, they'll not have a great experience, and things won't work. In this episode we'll check the account status before trying to save a record in CloudKit. We'll also respond to the notification to know when the user's account status has changed so we can react accordingly.

Episode Links

Checking Account Status

 func checkAccountStatus() {
        print("Checking account status:")
        let container = CKContainer.default()
        container.accountStatus { (accountStatus, error) in

            print("Account status: \(accountStatus.rawValue)")

            switch accountStatus {
            case .available:
                self.insertFirstRestaurant(container: container)

            case .noAccount:
                self.promptForICloud()

            case .couldNotDetermine:
                if let e = error {
                    print("Error checking account status: \(e)")
                }

            case .restricted:
                print("restricted")
            }
        }
    }

Handling Account Status Changes

        NotificationCenter.default.addObserver(forName: .CKAccountChanged,
                                               object: nil,
                                               queue: nil) { [weak self] (note) in
                                                print("Identity changed.")
                                                self?.checkAccountStatus()
        }

This episode uses Ios 10.2.