【问题标题】:How to save a location breadcrumb to CoreData in Swift如何在 Swift 中将位置面包屑保存到 CoreData
【发布时间】:2016-04-07 15:08:54
【问题描述】:

我正在尝试将用户旅程保存为 CoreData 中的面包屑导航,以便即使他们退出应用程序我也可以检索它。目前,下面的代码将他们的位置保存到 CloudKit,但我被告知为了检索他们的面包屑,最好将其保存到 Core Data。

只是想知道我该怎么做?

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

【问题讨论】:

  • 您会保存多个面包屑,还是只保存一个?

标签: swift core-data core-location


【解决方案1】:

由于您只保存一个面包屑位置,Core Data 不合适。如果您要保存一组需要显示、搜索等的面包屑,那么这可能是有意义的。

对于单个CLLocation,请使用NSUserDefaultsCLLocation 符合 NSCoding,因此您可以将其转换为 NSData 并保存:

let locationData = NSKeyedArchiver.archivedDataWithRootObject(location)
NSUserDefaults.standardUserDefaults().setObject(locationData, forKey: "breadcrumb")

读取数据时,查找"location" 的值,然后使用NSKeyedUnarchiver 将其转换回CLLocation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多