2016-07-20 117 views
2

我正在嘗試更新CloudKit中的現有記錄,但我正在創建新記錄而不是更改值!這是代碼:如何更新CloudKit中記錄類型的字段?

func pairing(phone: String, ctid: String) { 
    ctUsers = [CKRecord]() 
    print("THE PHONE IS: \(phone)\n") 

    let publicData = CKContainer.default().publicCloudDatabase 
    let predicate = Predicate(format: "phone == %@", phone) 
    let query = CKQuery(recordType: "Elder", predicate: predicate) 

    publicData.perform(query, inZoneWith: nil) { (results: [CKRecord]?, error: NSError?) -> Void in 
     if error != nil { 
      print(error?.localizedDescription) 
     } 

     if let users = results { 
      self.ctUsers = users 
      print("\nHow many users in cloud: \(self.ctUsers.count)\n") 

      if self.ctUsers.count != 0 { 

       let user = CKRecord(recordType: "Elder") 
       user["careTakerId"] = ctid 

       let publicData = CKContainer.default().publicCloudDatabase 
       publicData.save(user, completionHandler: { (record: CKRecord?, error: NSError?) in 
        if error == nil { 

         DispatchQueue.main.asynchronously(execute: {() -> Void in 
          print("CARETAKER updated successfully\n") 
         }) 
        } 
        else { 
         print("\nHUEHUEHUEHUE\n") 
         print(error?.localizedDescription) 
        } 
       }) 
      } 
      else { 
       print("\nELDER ISN'T IN CLOUD\n") 
       print(error?.localizedDescription) 
      } 
     } 
    } 
} 

快速的解釋:首先,我越來越老的電話號碼(每個老人都有不同的電話),並檢查該電話號碼是在雲中。如果是的話,那麼更新這位長輩的careTakerId,特別是!

在這裏你可以看到,在創建這個「NO NAME」記錄,上面記錄保持不變

任何想法?

+0

哦,不介意的語法,我使用的Xcode 8個beta 2個版本 –

回答

3

現在才意識到問題出在哪裏:

publicData.perform(query, inZoneWith: nil) { (results: [CKRecord]?, error: NSError?) -> Void in 
    if error != nil { 
     print(error?.localizedDescription) 
    } 

    if let users = results { 
     self.ctUsers = users 
     print("\nHow many users in cloud: \(self.ctUsers.count)\n") 

     if self.ctUsers.count != 0 { 

      let user = users.first //CKRecord(recordType: "Elder") 
      user?["careTakerId"] = ctid 

      let publicData = CKContainer.default().publicCloudDatabase 
      publicData.save(user, completionHandler: { (record: CKRecord?, error: NSError?) in 
       if error == nil { 

        DispatchQueue.main.asynchronously(execute: {() -> Void in 
         print("CARETAKER updated successfully\n") 
        }) 
       } 
       else { 
        print("\nHUEHUEHUEHUE\n") 
        print(error?.localizedDescription) 
       } 
      }) 
     } 
     else { 
      print("\nELDER ISN'T IN CLOUD\n") 
      print(error?.localizedDescription) 
     } 
    } 
} 

我是從字面上創建一個新的紀錄!我只需要訪問結果變量,即CKRecord的向量,然後更改並保存字段!

4

做它最簡單的方式,獲取該記錄,更新和保存:

let recordID = CKRecordID(recordName: "[record_name_here]") 

    database.fetch(withRecordID: recordID) { record, error in 

     if let record = record, error == nil { 

      //update your record here 

      self.database.save(record) { _, error in 
       completion?(error) 
      } 
     } 
    } 
+0

謝謝,非常有用。 – ChanWarde

相關問題