There's some logic in my app that first checks to see if a specific CloudKit record zone exists. If it doesn't, it creates the zone, and then my application continues on with its work.
The way I've implemented this right now is by catching the zoneNotFound
error when I call CKDatabase#recordZone(for:)
(docs) and creating the zone when that happens:
do {
try await db.recordZone(for: zoneID)
} catch let ckError as CKError
where [.zoneNotFound, .userDeletedZone].contains(ckError.code)
{
// createZone is a helper function
try await createZone(zoneID: zoneID, context: context)
}
This works great, but every time I do this, an error is logged in CloudKit Console, which creates a lot of noise and makes it harder to see real errors.
Is there a way to do this without explicitly triggering a CloudKit error?
I just found CKDatabase#recordZones(for:)
(docs), which seems like it returns an empty array instead of throwing an error if the zone doesn't exist.
Will calling that and looking for a non-empty array work just as well, but without logging lots of errors in the console?
I haven't double checked if recordZones(for:)
generates logs for CloudKit Console. My impression is that it doesn't. If you confirm that as well, I'd believe that the API works for you.
Alternatively, you can use fetchAllRecordZones to fetch all existing record zones, and check if your target record zone is there.
Note that the result you get reflects the situation at the moment when the server responds the request. If another peer happens to create the zone when the result is on its way to your device, the result you get will be different from the server truth. Your app still needs to be ready for handling that kind of corner case.
Best,
——
Ziqiao Chen
Worldwide Developer Relations.