Caleb Caleb - 1 year ago 86
Swift Question

Trying to modify ckrecord in swift

I want the users' location to be updated in cloudkit but my code just save a new record every time. How can the existing record be modified or replaced by the new one?

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
locationRecord.setObject(location, forKey: "location")
let publicData = CKContainer.defaultContainer().publicCloudDatabase
publicData.saveRecord(locationRecord) { record, error in
if error == nil
print("Location saved")
self.loc1 = location!

Answer Source

To Modify a record, you need to pull in your orignal record - update the details and then save the record.

I would do this by caching a reference to the original recordID eg

var locationRecordforUser = (whatever your CKrecord was when you created it)

then in your location method above, just grab it, make changes and perform save

 record.setValue(locationbits, forKey: locationField)
            self. publicData.saveRecord(record, completionHandler: { (savedRecord, error) in
              dispatch_async(dispatch_get_main_queue()) {
                  completion(savedRecord, error)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download