Getting Started With NSPersistentCloudKitContainer
Tags: swift, coredata, cloudkit, ios13
Published: 2019-06-14 11:54:41

---
title: Getting Started With NSPersistentCloudKitContainer
description: "Provides an example project and walkthrough for saving and syncing a single Core Data Entity with CloudKit using NSPersistentCloudKitContainer"
published: true
tags: Swift, Core Data, CloudKit, iOS 13
canonical_url: https://www.andrewcbancroft.com/blog/ios-development/data-persistence/getting-started-with-nspersistentcloudkitcontainer/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/eoov02000zerscg2u2d0.png
---

## First Things First

- In order to use `NSPersistentCloudKitContainer` in your app, you need to be targeting iOS 13+.
- The CloudKit syncing portion only works on physical devices (not in the simulator). That being the case, you’ll need two or more devices running the app and using the same iCloud account to fully test things out and make sure syncing and data merging behavior works as you’d expect it to.

The goal of this walkthrough is to provide you with a fully-working example of performing and synchronizing create, read, update, and delete operations using `NSPersistentCloudKitContainer`.

It’s the project I wish I had for referencing the basics…something **beyond** the out-of-the-box, saving a list of timestamps that comes pre-implemented with a Master-Detail app, but something **less complicated** than [Apple’s example project](https://developer.apple.com/documentation/coredata/synchronizing_a_local_store_to_the_cloud) which ends up having several relationships involved in the data model, extra features configured on the persistent container, etc.

I offer it to you as reference as well – I hope it helps!

Resources

- [Blog Idea List Example Xcode Project](https://github.com/andrewcbancroft/BlogIdeaList)
- [Using Core Data With CloudKit - WWDC 2019 Session 202](https://developer.apple.com/videos/play/wwdc2019/202)

## Setup

The easiest way to get stareted with `NSPersistentCloudKitContainer` is to enable Core Data and CloudKit when you start your new project.

![Enable Core Data and CloudKit](https://www.andrewcbancroft.com/blog/ios-development/data-persistence/getting-started-with-nspersistentcloudkitcontainer/enable-core-data-cloudkit.png)

### The Core Data + CloudKit Stack

Xcode provides the Core Data Stack code you need in the usual location: in the AppDelegate.swift file.

There’s one notable difference though. Instead of initializing a normal `NSPersistentContainer`, Xcode uses the new `NSPersistentCloudKitContainer` (this is why it’s important to check the CloudKit box when you create your app).

![NSPersistentCloudKitContainer](https://www.andrewcbancroft.com/blog/ios-development/data-persistence/getting-started-with-nspersistentcloudkitcontainer/nspersistentcloudkitcontainer-code.png)

### What About Existing Apps?

If you’ve got an existing app that’s using a “regular” `NSPersistentContainer`, you can change it to `NSPersistentCloudKitContainer` and continue on from there!

If you’re not using `NSPersistentContainer` with your app yet, [my guide on how to migrate](https://dev.to/andrewcbancroft/using-an-existing-sqlite-store-with-nspersistentcontainer-1o09-temp-slug-1652245) may be of help!

### Adding Capabilities

While Xcode auto-generates the Core Data + CloudKit stack for you, it does _not_ enable iCloud for you.

To enable full functionality, you need to go to your **Xcode project settings**.

Then click on the **Signing & Capabilities** section and add the **iCloud** and **Background Modes** capabilities.

Check the **CloudKit checkbox** , and the **Remote Notifications checkbox**.

#### Add iCloud + CloudKit

![Add iCloud with CloudKit](https://www.andrewcbancroft.com/blog/ios-development/data-persistence/getting-started-with-nspersistentcloudkitcontainer/add-icloud.gif)

#### Add Background Modes + Remote Notifications

![Add Background Modes with Remote Notifications](https://www.andrewcbancroft.com/blog/ios-development/data-persistence/getting-started-with-nspersistentcloudkitcontainer/add-background-modes.gif)

### What About Registering for Remote Notifications?

The beauty of `NSPersistentCloudKitContainer` is that it handles all the work required to listen for and respond to remote notifications.

This means that data saved locally on _one_ device gets pushed up to iCloud synced back down to _another_ device automatically.

### What About My Data Model in iCloud?

When you enable the iCloud capability for your app, Xcode automatically creates a container for your app in the CloudKit Dashboard.

It does _not_, however, create a schema that matches your Core Data model…yet. This is a setting you can toggle, but the default behavior is to “lazily” create the schema as people create objects and save them to your persistent store.

![Empty Schema](https://www.andrewcbancroft.com/blog/ios-development/data-persistence/getting-started-with-nspersistentcloudkitcontainer/empty-schema.gif)

## Walking Through the Example Project

WWDC always gets the blog ideas flowing through my brain, so this little app’s theme is “saving a list of blog ideas”, both locally, and _across_ my devices using `NSPersistentCloudKitContainer`.

### User Interface

The user interfacde allows you to perform the essential operations of a data-driven app: create, read, update, and delete objects.

![User Interface](https://www.andrewcbancroft.com/blog/ios-development/data-persistence/getting-started-with-nspersistentcloudkitcontainer/user-interface.png)

### Data Model

The data model for this is basic: a single `BlogIdea` Entity with two `String` properties: `ideaTitle` and `ideaDescription`.

![BlogIdea Data Model](https://www.andrewcbancroft.com/blog/ios-development/data-persistence/getting-started-with-nspersistentcloudkitcontainer/data-model.png)

No relationships or extra configuration options… just one Entity to keep it a basic reference-able project.

The `BlogIdea` NSManagedObject subclass is implemented like this:

```swift
 public class BlogIdea: NSManagedObject {
 
  @NSManaged public var ideaTitle: String?
  @NSManaged public var ideaDescription: String?
 
  static var entityName: String { return "BlogIdea" }
 }
```

### View Controllers

There are two view controllers that come with this example:

**MainViewController**

```swift
 class MainViewController: UIViewController, 
   NSFetchedResultsControllerDelegate, 
   UITableViewDataSource, 
   UITableViewDelegate {
   // Responsible for listing out BlogIdeas in a table view
  
   // Holds a reference to an NSManagedObjectContext instance
   // which gets initialized in the SceneDelegate.swift file
   // and passed to this view controller when the scene gets "connected"
  
   // Uses NSFetchedResultsController to keep the table view in sync
   // with the Core Data managed object context
  
   // Implements swipe-to-delete with delete confirmation
  
   // Navigates to editor when someone taps on a table view row
   // and passes its NSManagedObjectContext instance along
  }
```

**BlogIdeaEditorViewController**

```swift
 class BlogIdeaEditorViewController: UIViewController {
  // Responsible for creating new BlogIdeas
 
  // Holds a reference to an NSManagedObjectContext instance
  // which gets passed along in MainViewController's prepare for segue method
 
  // Able to edit existing BlogIdeas
 }
```

## Understanding the Default Sync Behavior

At this point no additional configuration has happened. The Core Data stack is the unmodified Xcode generated code, and the fetched results controller is hooked up to the managed object context for your app, ready to fetch Blog Ideas and help get them into the table view.

If you open the project, build and run on two devices, and begin adding Blog Ideas, updating them, deleting them, etc. what happens?

The first observation is that…things…don’t…seem to be working…

{% youtube DLAwrSCl3Cc %}

…At least not how I thought they would.

I _expected_ my Blog List view to automatically update in response to changes made on my other device, buuut… nope. Thankfully it’s an “easy” fix.

## Reflecting Changes in the UI

Wherever you access your app’s persistent CloudKit container to grab the `viewContext`, you need to set the `automaticallyMergesChangesFromParent` property to `true`.

I initialize the container in the `SceneDelegate`, so check out the code exerpt below to see where that gets set.

**SceneDelegate.swift**

```swift
 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
   // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
   // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
   // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
   guard let _ = (scene as? UIWindowScene) else { return }
      
   let navigationController = self.window?.rootViewController as! UINavigationController
   let mainVC = navigationController.viewControllers[ ] as! MainViewController
      
   let viewContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
   viewContext.automaticallyMergesChangesFromParent = true
  
   mainVC.managedObjectContext = viewContext
  }
```

Making this one-line change will enable the app (which is supported by `NSFetchedResultsController`) to update the UI in response to remote data changes…

**eventually**

It can be slow (anywhere from 5 to 15 seconds). But it will eventually update.

## Revisiting the iCloud Schema

Once you save an object, the schema within the iCloud Dashboard will update to reflect the properties you designed in your Core Data Model.

![Revisiting the Schema](https://www.andrewcbancroft.com/blog/ios-development/data-persistence/getting-started-with-nspersistentcloudkitcontainer/revisit-schema.png)

## Where’s My Data?

If you attempt to query for BlogIdea records in any of the iCloud databases provisioned for your app, you won’t find any.

Why?

That’s because Apple fully manages a hidden Zone for your Core Data + CloudKit data. It was veeeery briefly mentioned in the [WWDC 2019 presentation](https://developer.apple.com/videos/play/wwdc2019/202) (right about 10:50 if you’re watching).

## Wrapping Up

My hope was to provide you with a fully-working example of performing and synchronizing create, read, update, and delete operations using `NSPersistentCloudKitContainer`.

Check out the [GitHub repo](https://github.com/andrewcbancroft/BlogIdeaList), leave a comment, or [@ me on Twitter](https://twitter.com/andrewcbancroft) to continue the conversation from here!