ios - CoreLocation 类的 Codable 扩展

标签 ios swift core-location codable

我需要将 Codable 添加到两个类中。一个是 CLLocationCoordinate2D,第二个是 CLCircularRegion

我对 CLLocationCoordinate2D 没有任何问题,它可以通过这样做来工作:

extension CLLocationCoordinate2D: Codable {
    public enum CodingKeys: String, CodingKey {
        case latitude
        case longitude
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(latitude, forKey: .latitude)
        try container.encode(longitude, forKey: .longitude)
        }

    public init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        latitude = try values.decode(Double.self, forKey: .latitude)
        longitude = try values.decode(Double.self, forKey: .longitude)
    }
}

但是我在尝试用 CLCircularRegion 做同样的事情时遇到了很多问题。由于 radiuscenter 是只读属性,我无法真正以相同的方式创建它们。另一个问题是为什么我能够在 CLLocationCoordinate2D 中创建 public init 并在 CLCircularRegion 中创建 Codable 扩展我'我得到错误:

enter image description here

我看到了 public 的意思,但是需要吗?当然 required 会失败,因为它是扩展而不是类。所以这个问题的一个解决方案是创建抽象类,它将包含所有字段并在初始化程序中构建区域我知道,但是还有任何其他方法可以将 Codable 扩展到 Apple 尚不支持的现有类?

最佳答案

灵感来自 Artem answer我通过以 Double 格式将纬度和经度存储在对象中解决了我的问题。 CLLocation 然后作为读取两个存储值的计算属性返回:

private var latitude: Double = 0.0
private var longitude: Double = 0.0    

var location: CLLocation {
    return CLLocation(latitude: latitude, longitude: longitude)
}

在您使用 CLCircularRegion 的情况下,您还需要以类似的方式保存 radiuscenter

关于ios - CoreLocation 类的 Codable 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49388372/

相关文章:

swift - 核心数据获取请求不起作用

ios - 从 UITableViewCell 转到 ViewController 不工作

swift - 应用程序在前台使用 CoreML,GPU 在前台,当应用程序转到后台时,无法切换到 CPU

ios - Swift:错误:链接器命令失败,退出代码为 1

ios - 在什么情况下 CLAuthorizationStatus "restricted"?

ios - 设置自定义顶部/底部边界

ios - 在 UIImageView 中加载 gif 图像时减少内存消耗

ios - 将框架添加到现有的 Cocoapods 设置

ios - 通用 iOS 9.1 应用程序不兼容

ios - Swift - 在后台打开和关闭位置以节省电池