问题
Currently, my app pins a location and that location is stores like so:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
// Find location of user
var userLocation:CLLocation = locations[0] as! CLLocation
var latitude = userLocation.coordinate.latitude
var longitude = userLocation.coordinate.longitude
var latDelta:CLLocationDegrees = 0.01
var longDelta: CLLocationDegrees = 0.01
var span: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
var location:MKUserLocation = currentLocation;
var region: MKCoordinateRegion = MKCoordinateRegionMake(location.coordinate, span)
var coordinate:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude);
carInitialLocation = userLocation;
locationsDefaults.append(carInitialLocation);
carInitialCoordinate = coordinate;
self.map.setRegion(region, animated: true);
}
where locationsDefaults is the array where I store the location of the pin.
I would like to use NSUserdefaults, but i'm not really sure how i'd do that as it doesn't except non NS data. A guideline/structure in swift would be greatly appreciated!
回答1:
You can save NSData to NSUserDefaults. So all you need is to convert your CLLocation object to NSData using NSKeyedArchiver method archivedDataWithRootObject as follow:
// saving your CLLocation object
let locationData = NSKeyedArchiver.archivedDataWithRootObject(carInitialLocation)
NSUserDefaults.standardUserDefaults().setObject(locationData, forKey: "locationData")
// loading it
if let loadedData = NSUserDefaults.standardUserDefaults().dataForKey("locationData") {
if let loadedLocation = NSKeyedUnarchiver.unarchiveObjectWithData(loadedData) as? CLLocation {
println(loadedLocation.coordinate.latitude)
println(loadedLocation.coordinate.longitude)
}
}
来源:https://stackoverflow.com/questions/31464740/how-to-save-pin-annotation-once-app-is-closed-swift