swift - 如何在 Swift 中将位置面包屑保存到 CoreData

标签 swift core-data core-location

我正在尝试将用户旅程保存为 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
     }
}

最佳答案

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

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

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

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

关于swift - 如何在 Swift 中将位置面包屑保存到 CoreData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36480247/

相关文章:

NSManagedObject 的 Date 与 NSDate 的 Xcode 9 构建问题

ios - CLLocationManagerDelegate-locationManager(_ :startMonitoring:) not called when there is no network

iOS : push notification badge count not increase in this payload formate

ios - 通过 iOS App 发送 Facebook 好友请求

core-data - 查询/过滤具有共同父级且不符合键值的核心数据实体

ios - 如何使用 NSSet 填充 tableView? ( swift )

swift - 覆盖 Swift 字典创建以不允许 nil

ios - 可以在 Swift 应用程序和后端之间交换对象吗?

ios - Apple Watch coreLocation 错误 *** 断言失败 -[CLLocationManager requestLocation]

ios - Core Location 正常工作的超时时间