1

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

内容丰富的文档说他们的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.latitude错误locationCoord.longitude return的值(其中之一始终是0.0)。

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

4

1 回答 1

6

我认为,getBytes:length:fromNSData就足够了:

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 中没有。最简单的方法是使用.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

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;
于 2014-11-18T11:23:32.727 回答