Persisting Runtime state

Blog Post created by NFurness-esristaff Employee on Jan 25, 2017

The ArcGIS Platform runs on JSON. WebMaps are JSON. Service Definitions are JSON. Feature records are JSON. Our SDKs and APIs make use of this to make your life easier as a developer, of course, but this is also a great way to exchange objects (for example, geometries or graphics) between apps/devices/etc.


The iOS Runtime makes this easy with the AGSJSONSerializable protocol (other Runtime flavors offer the same functionality, but I'll talk about iOS here). 


Here's some sample Swift 3 code to serialize a map view's current viewpoint and restore it later…


1. When your app gets backgrounded, you might call this:


if let viewpoint = mapView.currentViewpoint(with: .centerAndScale) {
    do {
        let json = try viewpoint.toJSON()
        // Store the JSON somewhere. E.g. NSUserDefaults.
    } catch(let jsonEncodeError) {
        print("Error: \(jsonEncodeError)")


2. Later, when your app is reopened, read that JSON to create a new AGSViewpoint:


let json = // Read the JSON from wherever you stored it...
let map = // Load or create a map...

do {
    if let restoredViewpoint = (try? AGSViewpoint.fromJSON(json)) as? AGSViewpoint {
        map.initialViewpoint = restoredViewpoint
} catch(let jsonParseError) {
    print("Error: \(jsonParseError)")
} = map


If you already have a map associated with the map view, you can instead call AGSMapView.setViewpoint().