What type to cast array of CKRecord.References when adding to Database

60 views Asked by At

I have a CKRecord type "AccountInfo" which has a field "Wines" with is a list of references to "Wine" records. When I add a new wine, the wine record is added correctly and can reference its vineyard correctly but when I try and update the "AccountInfo" the "Wines" field stays the same.

Here's the code:

//reference wine in user record
        //Not working
        let cloudDB = CKContainer.default().publicCloudDatabase
        let userRecord = CKRecord(recordType: "AccountInfo", recordID: model.activeUser.recordID)
        var wineRecords: [CKRecord.Reference] = []
        for wine in model.activeUser.wines {
            wineRecords.append(CKRecord.Reference(recordID: wine.recordID, action: .deleteSelf))
        }
        
        userRecord.setValuesForKeys([
            "Wines": wineRecords as NSArray
        ])
        
        let updateWinesList = CKModifyRecordsOperation(recordsToSave: [userRecord])
        updateWinesList.savePolicy = .changedKeys
        
        //save changes to users wine list
        cloudDB.add(updateWinesList)

I've tried using CKModifyRecirdsOperation and saving the whole record with cloudDB.save but nothing has made any changes to the record. So can someone explain how to update a field of type Reference(List) in a CKRecord inside a Cloudkit database.

Edit: The major reason this is confusing me is because in my Wine record I have a field "Vineyard" which references a Vineyard record like so:

 let recordToAdd = CKRecord(recordType: "Wine")
        //get Vineyard Record
        recordToAdd.setValuesForKeys([
            "Type": newWine.type,
            "Vintage": newWine.vintage,
            //This works
            "Vineyard": CKRecord.Reference(recordID: vineyard.recordID, action: .deleteSelf)
        ])

Update 1/11 I've tested out the Modify operation with other fields so I know that it is syntaxically correct so I'm assuming it is an issue with the Type that I cast the array as. So can some provide insight on what the correct type casting is.

1

There are 1 answers

0
john elemans On

for reference, this code works;

func addCourseReferenceToDeck(deckN : Int, courseRef : CKRecord.Reference, completion: @escaping (Error?) -> Void)
{
    let deckRec = decks[deckN]

    var newCourseRefs = [CKRecord.Reference]()
    if deckRec["courses"] != nil
    {
        newCourseRefs = deckRec["courses"] as! [CKRecord.Reference]
    }
    newCourseRefs.append(courseRef)
    deckRec["courses"] = newCourseRefs
    
    privateDB.save(deckRec, completionHandler:
    {
            (record, error) -> Void in
            if (error != nil)
            {
                completion(error)
            }
            else
            {
                //self.decks.append(record!)
                completion(nil)
                
            }
           
    })
}

My record for decks has a field "courses" of type [CKRecord.Reference];