NSValue到Swift中的CLLocationCoordinate2D

sch*_*ler 1 nsvalue cllocationcoordinate2d swift ios8

我正在使用Contentful.com我的iOS应用程序作为内容后端.geo-point在我的Swift项目中,我不能让他们回到我身边.

Contentful文档说他们的API回报是" NSData与" CLLocationCoordinate2D 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
Run Code Online (Sandbox Code Playgroud)

然而,locationCoord.latitudelocationCoord.longitude return错误值(他们总是被一个0.0).

有人能告诉我这里我做错了什么,以及如何正常工作?谢谢.

rin*_*aro 5

我认为,getBytes:length:NSData足够的:

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

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

即:objCType:参数不期望类型名称"String",但期望"Type Encodings",在这种情况下是{?=dd}.在Objective-C中,你很方便@encode(TypeName),但不是在Swift中.最简单的方法是使用.objCType属性NSValue.

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
Run Code Online (Sandbox Code Playgroud)

而且,CDAEntry在Contentful SDK中似乎有确切的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;
Run Code Online (Sandbox Code Playgroud)