Search code examples
swiftlocationcloudkit

How to store users location on CloudKit in swift?


I'm trying to store a users journey and upload it to CloudKit.

The following takes the users location whenever they move more than 5 meters and uploads as a string but I want it to be uploaded as a location list or similar so it can be pulled down later.

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    let location = locations.last
    let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
    addCrumbPoint(center)

    let message = "{\"lat\":\(location!.coordinate.latitude),\"lng\":\(location!.coordinate.longitude), \"alt\": \(location!.altitude)}"

    let newSweet = CKRecord(recordType: "Sweet")
    newSweet["content"] = message

    let publicData = CKContainer.defaultContainer().publicCloudDatabase
    publicData.saveRecord(newSweet, completionHandler: { (record:CKRecord?, error:NSError?) -> Void in
        if error == nil {
            print("woo")
        }else{
            print(error)
        }
    })
}

The documentation on using Location and CloudKit is written in Objective-C so any help would be brilliant.

CloudKit

CLLocationManager


Solution

  • You create a CKRecordID and a CKRecord. Then you set the last retrieved CLLocation on the CKRecord.

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
      let location = locations.last!
      let id = CKRecordID(recordName: "01")
      let locationRecord = CKRecord(recordType: "location", recordID: id)
      locationRecord.setObject(location, forKey: "location")
      // or locationRecord["location"] = location
      let publicData = CKContainer.defaultContainer().publicCloudDatabase
      publicData.saveRecord(locationRecord) { record, error in
        //
      }
    }