Search code examples
ioscloudkit

how to create a location field in cloud kit


I'm trying to save a CKRecord with a location field along with it but when ever I try to it crashes. Here's the code I'm using (crashes where it says: // CRASHES HERE):

func saveStateMood(stateToSave:String) {

    // Create CK record
    let newRecord:CKRecord = CKRecord(recordType: "State")
    let newLocation:CKLocationSortDescriptor = CKLocationSortDescriptor(key: "Loco", relativeLocation: self.theState)
    newRecord.setValue(stateToSave, forKey: "State")
    newRecord.setValue(newLocation, forKey: "Loco") // CRASHES HERE!!!!!!

    // Save record into public database
    if let database = self.publicDatabase {

        database.saveRecord(newRecord, completionHandler: { (record:CKRecord!, error:NSError!) -> Void in

            // Check for error
            if error != nil {

                // There was an error
                NSLog(error.localizedDescription)

            }
            else {
                // There was no error
                dispatch_async(dispatch_get_main_queue()) {

                    // Refresh table
                    //self.retrieveStateMoods("")

                }

            }
        })
    }
}

(I'm using the CLGeocoder to find the current location then I assign the current location to "theState")

I'm trying to follow the CloudKit Quick Start guideline for adding location fields but it is all written in Obj-C and I can't seem to figure it out and I also can't figure out how to fetch the records by their location field either.


Solution

  • You need to store an instance of CLLocation in your record. But you are trying to save an instance of CKLocationSortDescriptor. Update your code to use CLLocation.