Search code examples
swiftnspersistentcloudkitcontainer

Can you share data with NSPersistentCloudKitContainer between multiple apps?


So my question is as written in the title if you could use NSPersistentCloudKitContainer to share data between different apps like if you have a different app for iPad, a different one for iPhone and a different one for Mac and if possible how would you do that? Thanks in advance!


Solution

  • Yes, you can, even across different platforms (macOS, iOS). I have done that several times, actually. All it takes is the same iCloud bundle ID. Click on Capability to select iCloud. Turn on the CloudKit checkbox button. Then select a specific bundle ID below.

    If you are going to use the same cloud container, you must be careful with the data types you use. For example, you shouldn't save UIImage or NSImage there because they are not exactly compatible with each other. In this case, you should save an image as Data.

    enter image description here

    Addition

    When you want to use a specific cloud container other than the (default) one that your project has automatically created, make sure you specify it in accessing the cloud database. That's the same for macOS and iOS.

    let cloudContainer = CKContainer(identifier: "iCloud.com.tomato.Eltomato")
    let publicDB = cloudContainer.publicCloudDatabase