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

时间:2016-04-06 10:15:44

标签: swift location cloudkit

我尝试存储用户旅程并将其上传到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

1 个答案:

答案 0 :(得分:1)

您创建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
    //
  }
}