Caleb Caleb - 1 year ago 103
iOS Question

Deleting CKRecord from Cloudkit in swift

I am trying to have the users' location be updated by this function. Originally it was saving the users' location every time, but I added the code that will be below the comment. How can I make sure the record that is being deleted is the old location?

let locationRecord = CKRecord(recordType: "location")

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!
//testing code below
let operation = CKModifyRecordsOperation(recordsToSave: nil, recordIDsToDelete: [locationRecord.recordID])
operation.savePolicy = .AllKeys
operation.modifyRecordsCompletionBlock = { added, deleted, error in
if error != nil {
} else {
print("location updated")

Answer Source

The best way to do this would be to update the existing one, as @Michael pointed out. The easy way to do this would be the first time you create the record, save the recordID to the defaults. For example,

let defaults = NSUserDefaults.standardUserDefaults()
var locationRecord:CKRecord

if defaults.objectForKey("locationRecordID") == nil{
    //Create a new record and save its id
    locationRecord = CKRecord(recordType: "location")
    defaults.setObject(locationRecord.recordID, forKey: "locationRecordID")
    //Fetch the already existing record
    let publicDB = CKContainer.defaultContainer().publicCloudDatabase
    publicDB.fetchRecordWithID((defaults.objectForKey("locationRecordID") as! CKRecordID), completionHandler{
        (record, error) in
        if error == nil{
          locationRecord = record
          print("Error fetching previous record")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download