How to save Pin Annotation once app is closed (Swift)

泄露秘密 提交于 2019-12-11 16:25:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!