Whenever my map view region changes, I'm saving the center and span values to NSUserDefaults so when the app is opened again it will be in the same place.
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue(myMapView.centerCoordinate.latitude, forKey: "lat")
defaults.setValue(myMapView.centerCoordinate.longitude, forKey: "long")
defaults.setValue(myMapView.region.span.latitudeDelta, forKey: "latDelta")
defaults.setValue(myMapView.region.span.longitudeDelta, forKey: "longDelta")
}
Here's where it is set from the defaults in my viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
let defaults = NSUserDefaults.standardUserDefaults()
if let lat = defaults.valueForKey("lat"),
let long = defaults.valueForKey("long"),
let latDelta = defaults.valueForKey("latDelta"),
let longDelta = defaults.valueForKey("longDelta")
{
let center: CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat as! Double, long as! Double)
let span: MKCoordinateSpan = MKCoordinateSpanMake(latDelta as! Double, longDelta as! Double)
let region: MKCoordinateRegion = MKCoordinateRegionMake(center, span)
myMapView.setRegion(region, animated: true)
}
}
However, when I open the app again, the region isn't shown as it was when the app was closed. The values that aren't saved correctly seem to be incremented by a constant value each time I close and reopen. What's going on?
I switched to using a dictionaryForKey approach, and here's the resulting dictionary upon 3 successive loads, without changing the map region at all:
["long": -95.78, "latDelta": 76.06, "lat": 37.13, "longDelta": 61.27]
["long": -95.78, "latDelta": 88.18, "lat": 31.93, "longDelta": 76.82]
["long": -95.78, "latDelta": 100.69, "lat": 25.71, "longDelta": 86.56]
The long value is saved properly, but the other 3 are behaving strangely.