将CLLocationCoordinate2D转换为可以存储的String [英] Converting CLLocationCoordinate2D to a String that can be stored
问题描述
我正在尝试在一个ViewController中保存用户的坐标,以便它可以用于创建可以在另一个ViewController中显示的注释。
I'm trying to save the coordinates of a user while in one ViewController so that it can be used to create an Annotation that can displayed in another ViewController.
在视图控制器中存储坐标我正在使用代码
In the view controller that stores the coordinates I'm using the code
NSUserDefaults.standardUserDefaults().setObject( Location, forKey: "Location")
在地图视图控制器,显示我正在尝试使用代码获取坐标的注释
In the map view controller that displays the annotation I'm trying to get the coordinates using the code
let Location = NSUserDefaults.standardUserDefaults().stringForKey("Location")
var Annotation = MKPointAnnotation()
Annotation.coordinate = Location
它告诉我类型 String?
的值类型为 CLLocationCoordinate2D
。
It is telling me that the value of type String?
to a value of type CLLocationCoordinate2D
.
那么如何将 CLLocationCoordinate2D
坐标转换为类型 String $的值c $ c>?
So how do I convert the CLLocationCoordinate2D
coordinates into a value of type String
?
推荐答案
通过这种方式,您可以将地点存储到 NSUserDefaults
:
This way you can store Locations to NSUserDefaults
:
//First Convert it to NSNumber.
let lat : NSNumber = NSNumber(double: Location.latitude)
let lng : NSNumber = NSNumber(double: Location.longitude)
//Store it into Dictionary
let locationDict = ["lat": lat, "lng": lng]
//Store that Dictionary into NSUserDefaults
NSUserDefaults.standardUserDefaults().setObject(locationDict, forKey: "Location")
之后您可以这样访问:
//Access that stored Values
let userLoc = NSUserDefaults.standardUserDefaults().objectForKey("Location") as! [String : NSNumber]
//Get user location from that Dictionary
let userLat = userLoc["lat"]
let userLng = userLoc["lng"]
var Annotation = MKPointAnnotation()
Annotation.coordinate.latitude = userLat as! CLLocationDegrees //Convert NSNumber to CLLocationDegrees
Annotation.coordinate.longitude = userLng as! CLLocationDegrees //Convert NSNumber to CLLocationDegrees
更新:
HERE 是您的示例项目。
这篇关于将CLLocationCoordinate2D转换为可以存储的String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!