gpt4 book ai didi

swift - Swift 中的 NSValue 到 CLLocationCoordinate2D

转载 作者:搜寻专家 更新时间:2023-11-01 06:10:16 24 4
gpt4 key购买 nike

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

Contentful 文档说他们的 API 返回“NSData with 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

但是,locationCoord.latitudelocationCoord.longitude 返回 错误值(其中之一始终是 0.0 ).

有人能告诉我我做错了什么,以及如何让它正常工作吗?谢谢。

最佳答案

我认为,NSData 中的 getBytes: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;

关于swift - Swift 中的 NSValue 到 CLLocationCoordinate2D,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26992369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com