如何在Swift中将位置面包屑保存到CoreData
我正在尝试将用户的旅程保存为CoreData中的面包屑,这样即使他们退出应用程序,我也可以检索它。目前,下面的代码将它们的位置保存到CloudKit,但我被告知,为了检索它们的面包屑,最好将其保存到核心数据 只是想知道我该怎么做如何在Swift中将位置面包屑保存到CoreData,swift,core-data,core-location,Swift,Core Data,Core Location,我正在尝试将用户的旅程保存为CoreData中的面包屑,这样即使他们退出应用程序,我也可以检索它。目前,下面的代码将它们的位置保存到CloudKit,但我被告知,为了检索它们的面包屑,最好将其保存到核心数据 只是想知道我该怎么做 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last!
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last!
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
addCrumbPoint(center)
// Add to Cloudkit
let locationRecord = CKRecord(recordType: "location")
locationRecord["location"] = location
let publicData = CKContainer.defaultContainer().publicCloudDatabase
publicData.saveRecord(locationRecord) {
record, error in
}
}
因为您只保存了一个面包屑位置,所以核心数据是不合适的。如果您正在保存需要显示、搜索等的面包屑集合,那么这可能是有意义的 对于单个
CLLocation
,请使用NSUserDefaults
CLLocation
符合NSCoding
,因此您可以将其转换为NSData
并保存:
let locationData = NSKeyedArchiver.archivedDataWithRootObject(location)
NSUserDefaults.standardUserDefaults().setObject(locationData, forKey: "breadcrumb")
读取数据时,请查找
“location”
的值,然后使用NSKeyedUnarchiver
将其转换回CLLocation
,因为您只保存一个面包屑位置,所以核心数据不合适。如果您正在保存需要显示、搜索等的面包屑集合,那么这可能是有意义的
对于单个CLLocation
,请使用NSUserDefaults
CLLocation
符合NSCoding
,因此您可以将其转换为NSData
并保存:
let locationData = NSKeyedArchiver.archivedDataWithRootObject(location)
NSUserDefaults.standardUserDefaults().setObject(locationData, forKey: "breadcrumb")
读取数据时,请查找
“location”
的值,然后使用NSKeyedUnarchiver
将其转换回CLLocation
您是要保存多个面包屑,还是只保存一个?您是要保存多个面包屑,还是只保存一个?