CloudKit - How to save a record if it does not exist

I am trying to create a record type containing unique values ​​and will act as the target of the link in another record type. For example, Record Type - Movies will contain a unique list of movies provided by users. And FavoriteMovies will contain a "Users" link and a link to movies. Users can select from the list of existing films or add new ones to it.

The problem occurs if I create a new Cinema record and another user creates a new record with the same name (after I received the list of films, but before I try to add a new one). Two new records are considered different records with different record identifiers. This means that as soon as I save the new one, there will be two copies of the films with the name save.

I can’t find a way to perform the “Save If Doesn't Exist” operation in the “Movie Recording Type”. I could save on completing the query request, but these two actions would not be an atomic transaction to guarantee uniqueness. As far as I know, this also happens with the CKQueryOperation chain with CKModifyRecordsOperation .

Is there a way to insert a record only if the value does not exist in one transaction?

+6
source share
1 answer

If I understand your use case correctly, you can make movieRecord.recordID.recordName the name of the movie and use CKModifyRecordsOperation with savePolicy IfServerRecordUnchanged to save efficiently if it does not exist. Then it will return an error that can be ignored if you try to save a record that already exists on the server:

 let saveRecordsOperation = CKModifyRecordsOperation() saveRecordsOperation.recordsToSave = [movieRecord] saveRecordsOperation.savePolicy = .IfServerRecordUnchanged 

Using savePolicy IfServerRecordUnchanged this operation will save the new video if it does not already exist on the server ("Save if it doesn’t exist"), but will return an error below if you try to overwrite a movie record that already exists on the server (provided that it not a new modified version of the record received from the server):

 <CKError 0x14d23980: "Server Record Changed" (14/2017); server message = "record to insert already exists"> 

You can handle this conflict in perRecordCompletionBlock , but in your specific use case you can just do nothing with the conflict error, so each movie entry will be the first record saved with this CKRecordID.

+6
source

Source: https://habr.com/ru/post/972332/


All Articles