Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
880 views
in Technique[技术] by (71.8m points)

ios - Converting CLLocationCoordinate2D to a String that can be stored

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    

It is telling me that the value of type String? to a value of type CLLocationCoordinate2D.

So how do I convert the CLLocationCoordinate2D coordinates into a value of type String?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")

After that you can access it this way:

//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

UPDATE:

HERE is your Example project.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...