【问题标题】:NSValue to CLLocationCoordinate2D in SwiftNSValue 到 Swift 中的 CLLocationCoordinate2D
【发布时间】:2014-11-18 10:45:59
【问题描述】:

我使用Contentful.com 作为我的iOS 应用程序的内容后端。我无法让他们的geo-point 在我的Swift 项目中为我工作。

Contentful 文档说他们的 API 返回“NSDataCLLocationCoordinate2D struct”。

我在我的项目中使用NSValue 来解决这个问题,但我无法让它正常工作。这是我的代码:

var locationCoord:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0,longitude: 0)

var locationData:NSData = entry.fields["location"] as NSData

var locationValue:NSValue = NSValue(bytes: locationData.bytes, objCType: "CLLocationCoordinate2D")

locationCoord = locationValue.MKCoordinateValue

但是,locationCoord.latitudelocationCoord.longitude return 值错误(其中一个始终是 0.0)。

谁能告诉我我在这里做错了什么,以及如何使它正常工作?谢谢。

【问题讨论】:

    标签: swift ios8 nsvalue cllocationcoordinate2d


    【解决方案1】:

    我认为,来自NSDatagetBytes:length: 就足够了:

    var locationData = entry.fields["location"] as NSData
    var locationCoord = CLLocationCoordinate2D(latitude: 0, longitude: 0)
    locationData.getBytes(&locationCoord, length: sizeof(CLLocationCoordinate2D))
    

    顺便说一句,为什么你的代码不起作用?

    即:objCType: 参数不期望类型名称“String”,而是期望"Type Encodings",在本例中为{?=dd}。在 Objective-C 中,你有方便的 @encode(TypeName),但在 Swift 中没有。最简单的方法是使用NSValue.objCType 属性。

    var locationData = entry.fields["location"] as NSData
    var locationCoord = CLLocationCoordinate2D(latitude: 0, longitude: 0)
    var objCType = NSValue(MKCoordinate: locationCoord).objCType // <- THIS IS IT
    var locationValue = NSValue(bytes: locationData.bytes, objCType: objCType)
    locationCoord = locationValue.MKCoordinateValue
    

    此外,Contentful SDK 中的CDAEntry 似乎有the exact API,我认为你应该使用这个:

    /**
     Retrieve the value of a specific Field as a `CLLocationCoordinate2D` for easy interaction with
     CoreLocation or MapKit.
    
     @param identifier  The `sys.id` of the Field which should be queried.
     @return The actual location value of the Field.
     @exception NSIllegalArgumentException If the specified Field is not of type Location.
     */
    -(CLLocationCoordinate2D)CLLocationCoordinate2DFromFieldWithIdentifier:(NSString*)identifier;
    

    【讨论】:

    • 仅供参考,当使用代码获取 CLLocationCoordinate2D 的 objCType 时,不要忘记import MapKit
    猜你喜欢
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    相关资源
    最近更新 更多