2014-11-18 6 views
1

iOS 앱의 콘텐츠 백엔드로 Contentful.com을 사용하고 있습니다. 내 Swift 프로젝트에서 저의 geo-point 복귀를 저에게 돌려 줄 수는 없습니다.Swift에서 NSValue to CLLocationCoordinate2D

콘텐츠 설명서에 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.longitudereturn 잘못된 값 (그 중 하나는 항상 0.0 인) : 여기에 내 코드입니다.

누군가 내가 잘못하고있는 것을 말해 줄 수 있습니까?이 작업을 올바르게 수행하는 방법은 무엇입니까? 감사.

답변

5

나는 NSData에서 getBytes:length:이 충분하다 생각 :

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

BTW, 왜 코드가 작동 doen't?

objCType: 매개 변수의 유형이 "문자열"이 아니지만, "Type Encodings" 일 것으로 예상합니다.이 경우는 {?=dd}입니다. Objective-C에서는 Swift가 아닌 @encode(TypeName)을 사용할 수 있습니다. 이를 얻는 가장 쉬운 방법은 .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 

또한, 그것은 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; 
+0

코드는 잘 작동을 제공했다. 고맙습니다. – schnabler

+0

FYI CLLocationCoordinate2D에 대한 objCType을 얻기 위해 코드를 사용할 때'import MapKit'을 잊지 마라. – johnboiles