Assuming you’ve added the CloudKit entitlements in the starter project, you are ready to add code in the CloudKit project class files to interact with the CloudKit private and public database. Before, we do so though, you have to authenticate the app user.
To authenticating the app user, you will add code in the app class files to perform these tasks:
- Declare and a boolean variable called userSignedIn and initialize it so it holds the value, false.
- In an if statement, check the NSFileManager’s opaque property, ubiquityIdentityToken to see if it is empty. If it is, re-initialize the userSignedIn variable so it holds the value, true.
- If the userSignedIn variable contain the value false, show the app user a message telling her to sign into her iCloud account, turn on iCloud Drive, and re-launch the CloudKit app.
- If the userSignedIn variable contain the value true, go ahead and process code in the class file that interact with the CloudKit’s public database and display messages in the textView.
The first two tasks will be performed in the AppDelegate.swift file. The last two tasks will be performed in the mainView.swift file; because that’s where we’ll use the CloudKit framework’s classes to interact with the CloudKit database.
Code presented on this page assume you are using Xcode 6.4 and Swift version 1.2. So if you are using a newer version of Swift, it may produce errors. Fix them by using Xcode’s Fix-it tool. I assume you are a registered member of Apple’s iOS Developer Program, and you have a real iPhone/iPad device to test the CloudKit code presented here. |
Before you get started in adding code in the AppDelegate.swift file and the MainViewController.swift file to authenticate the app user, take a look at Figure 1-3 below. As you can see in the Figure 1, I’ve already entered some basic code and comments in the mainViewController class.
Figure 1: Assistant editor view of the mainView and its class file | |
Figure 2: Default view of the mainView | Figure 3: Result of clicking the Execute Code button on the mainView |
The User Authentication Code
Here’s the user authentication code to add in the AppDelegate.swift file and the mainViewController.swift file.
Listing 1: AppDelegate.swift
Listing 2: mainViewController.swift
Test The User Authentication Code
If you signed into your iCloud account, turned on iCloud Drive via the Settings app, then launch the app in the iPhone 6 Simulator, you will see output shown in Figure 4 below. If you signed out of your iCloud account and/or turned off iCloud Drive via the Settings app, then launch the app in the simulator. You will see output shown in Figure 5.
Figure 4 | Figure 5 |