Sharing Core Data With CloudKit in SwiftUI

Learn to share data between CoreData and CloudKit in a SwiftUI app. By Marc Aupont.

4.7 (9) · 5 Reviews

Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Challenge Two

There’s one minor bug with your app at the moment. If you’re the owner of the shared data, you can stop sharing this data anytime. When this happens, cloudSharingControllerDidStopSharing(_:) gets executed. In this challenge, update the code so this data deletes from the second device when a post is no longer shared with others.

Did you figure it out? See the solution below:

[spoiler title=”Solution 2″]
Open CoreDataStack.swift. Under isShared(object:), add:

func isOwner(object: NSManagedObject) -> Bool {
  guard isShared(object: object) else { return false }
  guard let share = try? persistentContainer.fetchShares(matching: [object.objectID])[object.objectID] else {
    print("Get ckshare error")
    return false
  }
  if let currentUser = share.currentUserParticipant, currentUser == share.owner {
    return true
  }
  return false
}

The method:

  • Checks if the object has an associated CKShare. If not, it immediately returns false.
  • Attempts to get CKShare via the fetchShares(_:) method. If it doesn’t find any matching shares, it returns false.
  • Last, if the current user of that share is the owner, returns true. Otherwise, it returns false.

With this code in place, open CloudSharingController.swift and add the following code to cloudSharingControllerDidStopSharing(_:):

if !stack.isOwner(object: destination) {
  stack.delete(destination)
}

That’s it! Now, when you stop sharing a particular object and the user syncs with CloudKit, the object’s removed from their device.
[/spoiler]

Where to Go From Here?

You can download the completed project files by clicking the Download Materials button at the top or bottom of the tutorial.

In this tutorial, you learned the important steps to share Core Data with CloudKit, including:

  • Using NSPersistentCloudKitContainer to share the data.
  • Presenting a cloud-sharing view.
  • Accepting share invitations and fetching the shared data.
  • Differentiating private data and shared data in SwiftUI.

You learned the new methods introduced in iOS 15 and solved challenges and minor bugs in the app.

For more information, check Apple’s video on Build apps that share data through CloudKit and Core Data.

Here’s Apple’s sample project on Synchronizing a Local Store to the Cloud.

If you have any questions or comments, please join the forum discussion below.