I am interested in checking if a RecordZone has been shared. When I share a zone, I know there is a share record created in that zone. From Apple's CloudKit example:
func fetchOrCreateShare(contact: Contact) async throws -> (CKShare, CKContainer) {
guard let existingShare =
contact.associatedRecord.share else {
let share =
CKShare(rootRecord:contact.associatedRecord)
share[CKShare.SystemFieldKey.title] = "Contact: \.
(contact.name)"
_ = try await database.modifyRecords(saving:
[contact.associatedRecord, share], deleting: []).
return (share, container)
}
guard let share = try await database.record(for:
existingShare) as? CKShare else {
throw ViewModelError.invalidRemoteShare
}
return (share, container)
}
The first line of the method
guard let existingShare = contact.associatedRecord.share
checks if a specific record is being shared, but in the case of a shared zone, given a zone name, how can I check the .share
of that zone? When I try CKRecordZone(zoneName: "Contacts").share
, the value is nil even though the zone is being shared.
The CKRecordZone
should indeed have a non-nil share
property on it if it has been shared, however CKRecordZone(zoneName: "Contacts").share
won't work as that code is simply creating a new CKRecordZone
object locally and doesn't yet know about the share
property.
You would need to fetch the CKRecordZone
, and it's also worth pointing out the share
property is a CKRecord.Reference
, so to get the actual CKShare
object, your code would look something like this:
let contactZoneID = CKRecordZone.ID(zoneName: "Contacts")
let contactsZone = try await database.recordZone(for: contactZoneID) // Fetches zone from CloudKit.
if let shareReference = contactsZone.share { // This should be non-nil if the zone is shared.
let share = try await database.record(for: shareReference.recordID) as? CKShare
}