Environment: iOS/Swift 3
Goal: to save a AGSPolyline object within a dictionary for UserDefaults; and retrieve the object back as a AGSPolyline
Modus Operandi: storing the AGSPolyline within a dictionary for persistent UserDefault.
The following code is my first attempt; it crashes due to the AGSPolyline object not being serialized.
I thought I cut use the NSKeyedArchiver, being that AGSPolyline is an NSObject. But it fails with a run-time crash:
func storeSketch(doodle:AGSPolyline) {
var myDict = [String:AnyObject]()
var key = SketchItem.Polyline.desc()
let json = doodle.encodeToJSON()
let myData = NSKeyedArchiver.archivedData(withRootObject: doodle)
myDict[key] = myData as AnyObject?
key = SketchItem.Doodle.desc()
UserDefaults.standard.set(myDict, forKey: key)
return
}
I believe I need to JSON-SERIALIZE (and JSON-DE-SERIALIZE) my AGSPolyline object (a Geometry object) so I can insert it into my dictionary for UserDefaults storage.
How do I do that?
What's the syntax?
... or can I transform a AGSPolyline object to a common NSObject (NSData??)... and go from there?
Thank you for your question! You are correct, you will need to serialize and deserialize your AGSPolyline object so you can use it in your dictionary. The AGSPolyline class (and all geometry classes), inherits from the AGSJSONSerializable protocol. You can use the `toJSON` and `fromJSON` methods from that protocol to do what you need:
// convert a Polyline to a JSON representation
let polylineJSON = (try? polyline.toJSON()) as? NSDictionary
// create a new Polyline from JSON
let polyline2 = (try? AGSPolygon.fromJSON(polylineJSON!)) as! AGSPolyline
Thanks for the speedy reply!
I was thinking...
Perhaps converting the AGSPolyLine to a Swift Array: doodle.parts.array() as? Array
...where 'doodle' is a free-form sketch of type AGSPolyLine.
Then I could transform the Array into a NSData item for serialization.
Of course I would have to reverse all this back to AGSPolyLine.
... is this possible?
In the meantime, I'll go the JSON route per your example.
I got persistence!
I was able to serialize and de-serialize an AGSPolyLine (free sketch):
let lineSymbol = AGSSimpleLineSymbol(style: .solid, color: UIColor.red, width: 3)
let myPolyLine = UserDefaults.standard.value(forKey: SketchItem.Doodle.desc())
let polyline2 = (try? AGSPolygon.fromJSON(myPolyLine!)) as! AGSPolyline
graphicsOverlay.graphics.add(AGSGraphic(geometry: polyline2, symbol: lineSymbol, attributes: nil))
mapView.graphicsOverlays.add(graphicsOverlay)
I'll cleanup the code.... but it works.
Again, Thanks for your speedy answer!
Converting to a Swift array is possible, but you'd have to take into account multiple parts with multiple points per part, so you couldn't just do "doodle.parts.array() as? Array". The JSON route is the way to go and is fairly straightforward. Let us know if you have problems or can't get it to work.