小编典典

将CLLocationCoordinate2D转换为可以存储的字符串

swift

我试图在一个ViewController中保存用户的坐标,以便可以将其用于创建可以在另一个ViewController中显示的注释。

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

NSUserDefaults.standardUserDefaults().setObject( Location, forKey: "Location")

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

let Location = NSUserDefaults.standardUserDefaults().stringForKey("Location")
var Annotation = MKPointAnnotation()
Annotation.coordinate = Location

告诉我,type String?的值改为type 的值CLLocationCoordinate2D

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


阅读 575

收藏
2020-07-07

共1个答案

小编典典

这样,您可以将“位置”存储到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

更新:

这里是您的示例项目。

2020-07-07