Wismin
Wismin

Reputation: 1145

How to initialize CKRecord with both zoneID and recordID?

I'm currently building a solution to sync Core Data records to CloudKit.

I need help to find out it what I want to do with CKRecord is feasible.

I’ve checked the Apple CloudKit documentation, experiment and searched the web, but I didn’t find the kind of answer I want.

I would like to initialize the CKRecord with having zoneID and also recordID that I would supply in init method.
The initializer seems to force me to choose between the two. I want to create my own ZoneID (not using default), and also set the recordID instead of having it being autogenerated.

Would that be possible?

Upvotes: 6

Views: 1892

Answers (3)

Zoef
Zoef

Reputation: 228

Previously it was possible to initialize a CKRecord using a recordID and zoneID. However this has been deprecated:

 @available(swift, introduced: 4.2, deprecated: 4.2, message: "Use init(recordType:recordID:) + CKRecord.ID(zoneID:) instead")
public convenience init(recordType: CKRecord.RecordType, zoneID: CKRecordZone.ID)

However it seems that it is possible to do it this way using an undocumented and therefore I assume unreliable initializer:

let recordID = CKRecord.ID(zoneID: myZoneID) //This initializer is not documented!!! 
let record = CKRecord(recordType: "aString", recordID: recordID)

Upvotes: 0

garafajon
garafajon

Reputation: 1468

I made an extension on CKRecord so code changes were minimal:

extension CKRecord {
    static func with(recordType: CKRecord.RecordType, zoneID: CKRecordZone.ID) -> CKRecord {
        let recordID = CKRecord.ID(recordName: UUID().uuidString, zoneID: zoneID)
        return CKRecord(recordType: recordType, recordID: recordID)
    }
}

so instead of this (old broken way):

let myRecord = CKRecord(myType, zoneID: myZoneId)

it becomes:

let myRecord = CKRecord.with(myType, zoneID: myZoneId)

Note that the original method would generate a record name for you and I did that using UUID, which is probably the most standard way nowadays. Correct me if I'm wrong.

Upvotes: 0

Paulw11
Paulw11

Reputation: 115104

You can specify both a zone ID and a record ID, but you need to do it in three steps:

First, create a CKRecordZoneID with your zone ID and user:

let ckRecordZoneID = CKRecordZoneID(zoneName: "myZone", ownerName: CKOwnerDefaultName)

Then you can created a CKRecordID with your required record ID and specifying your CKRecordZoneID:

let ckRecordID = CKRecordID(recordName: recordIDString, zoneID: ckRecordZoneID)

Finally you can create the CKRecord using that record ID:

let ckRecord = CKRecord(recordType: myRecordType, recordID: ckRecordID)

Upvotes: 12

Related Questions