如何在 swift 中存储 CloudKit 上的用户位置?

How to store users location on CloudKit in swift?

我正在尝试存储用户旅程并将其上传到 CloudKit。

以下内容会在用户移动超过 5 米时获取用户位置并作为字符串上传,但我希望将其作为位置列表或类似内容上传,以便稍后可以将其拉下。

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)
        }
    })
}

有关使用 Location 和 CloudKit 的文档写在 Objective-C 中,因此任何帮助都会很棒。

CloudKit

CLLocationManager

您创建了一个 CKRecordID 和一个 CKRecord。然后在 CKRecord 上设置最后检索到的 CLLocation。

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
    //
  }
}