我试图在一个ViewController中保存用户的坐标,以便可以将其用于创建可以在另一个ViewController中显示的注释。
在存储我正在使用代码的坐标的视图控制器中
NSUserDefaults.standardUserDefaults().setObject( Location, forKey: "Location")
在显示注释的地图视图控制器中,我尝试使用代码获取坐标
let Location = NSUserDefaults.standardUserDefaults().stringForKey("Location") var Annotation = MKPointAnnotation() Annotation.coordinate = Location
告诉我,type String?的值改为type 的值CLLocationCoordinate2D。
String?
CLLocationCoordinate2D
那么如何将CLLocationCoordinate2D坐标转换为type的值String?
String
这样,您可以将“位置”存储到NSUserDefaults:
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
更新:
这里是您的示例项目。