Sharing Core Data objects between iCloud users (1)

66 阅读2分钟

Sharing Core Data objects between iCloud users

Use Core Data and CloudKit to synchronize data between devices of an iCloud user and share data between different iCloud users.

摘自:developer.apple.com/documentati…

1. Implement a custom sharing flow

Apps can implement a custom sharing flow when the system sharing UI is unavailable or doesn’t fit. The sample app performs the following tasks so users can share photos from watchOS:

  1. It creates a share using share(_:to:completion:) when an owner shares a photo.

截屏2025-05-19 11.03.52.png

  1. It configures the share with appropriate permissions, and adds participants for a share. A share is private if its publicPermission is .none. For shares that have a public permission more permissive than .none (called public shares), users can participate by tapping the share link, so there’s no need to add participants beforehand. The sample app looks up participants using fetchParticipants(matching:into:completion:), configures the participant permission using CKShare.Participant.permission, and adds it to the share using addParticipant(_:).

截屏2025-05-19 11.11.10.png

  1. It allows users to deliver the share URL (CKShare.url) to a participant using ShareLink.

  2. It implements userDidAcceptCloudKitShare(with:) to accept the share using acceptShareInvitations(from:into:completion:). After the acceptance synchronizes, the photo and its relationships are available in the participant’s shared persistent store.

截屏2025-05-19 11.17.34.png

  1. It manages the participants using addParticipant(_:) and removeParticipant(_:) from the owner side, or stops the sharing or participation by calling purgeObjectsAndRecordsInZone(with:in:completion:). (The purge API deletes the zone from CloudKit, and also the object graph from the Core Data store. Apps that need to keep the object graph can make a deep copy, ensure the new graph doesn’t connect to any share, and save it to the store.). In this process, the sample app calls persistUpdatedShare(_:in:completion:) when it changes the share using CloudKit APIs for NSPersistentCloudKitContainer to update the store.

截屏2025-05-19 11.21.33.png

截屏2025-05-19 11.22.22.png

截屏2025-05-19 11.57.47.png

Note

To be able to accept a share when people tap a share link, an app’s Info.plist file needs to contain the CKSharingSupported key with a value of true.