Reputation: 1945
I've written a method to save records in a custom zone and it seems to be working as expected. One thing I'm not sure about, however, is the CKRecord.ID
recordName
. Right now I just use a UUID
string. Is there a preferred way to assign the recordName
? Current CloudKit examples are pretty scarce and it seems like a decent portion of the CK documentation is outdated. Thanks.
func saveToCloud(record: String, recordType: String, recordTypeField: String, reference: CKRecord?, referenceType: String?) {
let zoneID = CKRecordZone.ID(zoneName: Zone.test, ownerName: CKRecordZone.ID.default.ownerName)
let recordID = CKRecord.ID(recordName: UUID().uuidString, zoneID: zoneID)
let newRecord = CKRecord(recordType: recordType, recordID: recordID)
if let reference = reference, let referenceType = referenceType {
let newReference = CKRecord.Reference(record: reference, action: .none)
newRecord[referenceType] = newReference
}
newRecord[recordTypeField] = record
database.save(newRecord) { (_,error) in
if let err = error as? CKError {
print("ERROR =" , err.userInfo )
}
}
}
Upvotes: 1
Views: 1896
Reputation: 1458
I agree that UUID is ideal. Example:
let newId = CKRecord.ID(recordName: UUID().uuidString)
However, it is important to not try to create one with invalid characters or with zero length string. The result is a fatal error! So, when loading them from an untrusted source (like parsing from server output) I use a safety function as follows:
extension CKRecord.ID {
public static func fromUntrusted(_ string: String?) -> CKRecord.ID? {
guard let string = string else { return nil }
guard let _ = string.data(using: .ascii, allowLossyConversion: false) else { return nil }
guard string.count > 0 && string.count < 255 else { return nil }
return CKRecord.ID(recordName: string)
}
}
usage:
if let recordId = CKRecord.ID.fromUntrusted(response) {
// use value
}
Upvotes: 3
Reputation: 4077
In my experience, it is best to generate record name from the record key, i.e. from a combination of fields that must be unique.
This way you can guarantee uniqueness even if you would mistakenly try to add the same record twice.
AFAIK, there is no other way of making certain field combinations unique in CloudKit.
Upvotes: 0
Reputation: 1349
From my point of view its very clear in the docs of CKRecord.ID:
A record ID object consists of a name string and a zone ID. The name string is an ASCII string not exceeding 255 characters in length. For automatically created records, the ID name string is based on a UUID and is therefore guaranteed to be unique. When creating your own record ID objects, you are free to use names that have more meaning to your app or to the user, as long as each name is unique within the specified zone. For example, you might use a document name for the name string.
Upvotes: 1