Duzmac
Duzmac

Reputation: 441

How to know if the CloudKit Zone exists already

To add a CKRecord in a private CKRecordZone you need to make sure the zone exists already.

But does it mean that every time I need to insert a record I need to fetch all the zones and find if my zone exists using fetchAllRecordZonesWithCompletionHandler ? It wouldn't be very efficient.

What is the best strategy to adopt ?

Most of the examples I have seen show how to create a zone and add a record into it. But you are not going to create the zone every time, and you can't just assume it exists...

Code below will fail if the zone has not been created already

let customZone = CKRecordZone(zoneName: self.zoneName!)
// Create a CKRecord
let lessonRecord = CKRecord(recordType: self.recordType, zoneID: customZone.zoneID)

Thanks for your help.

Upvotes: 8

Views: 2122

Answers (2)

Markv07
Markv07

Reputation: 276

Another way to avoid checking if a zone exists or not is to handle the error message when trying upload a record to a zone that does not exist. Since most records will succeed in the upload, this would seem more efficient.

database.save(record) { record, error in
    if record != nil, error == nil {
        print("** Saved new record in iCloud")
    } else {
        if let error = error as? CKError, error.code == .zoneNotFound {
            self.createNewZone(zone: cZone)
        }
    }
}

Upvotes: 0

rmaddy
rmaddy

Reputation: 318794

To see if a specific zone exists, use CKFetchRecordZonesOperation and pass just the one record zone ID.

You only need to do this once if your code is setup properly.

Create a class that represents a record zone. This class should perform all of the CloudKit operations for a given zone. When you initialize an instance of this class for a specific zone, you can check to see if the zone exists. If not, then create the zone. Then you use that specific instance of this zone helper class each time you need to read or write data to that zone.

Of course every read and write operation needs to check error results to check for CKErrorZoneNotFound errors. Getting such an error probably means the zone was deleted from another copy of the app.

Upvotes: 10

Related Questions