将CLLocationCoordinate2D转换为可以存储的String

Tri*_*ips 4 location nscoding cllocation ios swift

我正在尝试在一个ViewController中保存用户的坐标,以便它可以用于创建可以在另一个ViewController中显示的Annotation.

在视图控制器中,我使用代码存储坐标

NSUserDefaults.standardUserDefaults().setObject( Location, forKey: "Location")
Run Code Online (Sandbox Code Playgroud)

在地图视图控制器中显示我正在尝试使用代码获取坐标的注释

let Location = NSUserDefaults.standardUserDefaults().stringForKey("Location")
var Annotation = MKPointAnnotation()
Annotation.coordinate = Location    
Run Code Online (Sandbox Code Playgroud)

它告诉我type的值为type String?的值CLLocationCoordinate2D.

那么如何将CLLocationCoordinate2D坐标转换为类型的值String

Dha*_*esh 7

这样您就可以将地点存储到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")
Run Code Online (Sandbox Code Playgroud)

之后,您可以通过以下方式访问它:

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

更新:

是你的示例项目.