Hello.
I have an application where a map is located on one of the tabs. The application tracks movement of an object and draws a polyline of such movement. The code is like this:
var polylineFlight : MKGeodesicPolyline!
func drawFlightPath(Latitude latitude: String?, Longitude longitude: String?)
{
// Extract a saved polyline
let defaultsLoad = UserDefaults.standard
let polylineFlightData = defaultsLoad.object(forKey: "PolylineFlightData") as? NSData
if let polylineFlightData = polylineFlightData
{
self.polylineFlight = NSKeyedUnarchiver.unarchiveObject(with: polylineFlightData as Data) as! MKGeodesicPolyline!
}
if appSingleton.isConnectionAvailableShared == true
{
if self.previousLatitude == nil && self.previousLongitude == nil && latitude != nil && longitude != nil
{
self.previousLatitude = latitude!
self.previousLongitude = longitude!
}
else if self.previousLatitude != nil && self.previousLongitude != nil && latitude != nil && longitude != nil
{
if self.previousLatitude == latitude && self.previousLongitude == longitude
{
}
else
{
var routeCoordinates = [CLLocationCoordinate2D](repeating: CLLocationCoordinate2D(), count: 2)
var currentCoordinates = CLLocationCoordinate2D()
var previousCoordinates = CLLocationCoordinate2D()
let currentLatitudeDouble : Double? = Double(latitude!)!
let currentLongitudeDouble : Double? = Double(longitude!)!
let previousLatitudeDouble : Double? = Double(self.previousLatitude!)!
let previousLongitudeDouble : Double? = Double(self.previousLongitude!)!
if currentLatitudeDouble != nil &&
currentLongitudeDouble != nil &&
previousLatitudeDouble != nil &&
previousLongitudeDouble != nil
{
currentCoordinates = CLLocationCoordinate2DMake(currentLatitudeDouble!.roundTo(Places: 8), currentLongitudeDouble!.roundTo(Places: 8))
previousCoordinates = CLLocationCoordinate2DMake(previousLatitudeDouble!.roundTo(Places: 8), previousLongitudeDouble!.roundTo(Places: 8))
routeCoordinates[0] = previousCoordinates
routeCoordinates[1] = currentCoordinates
let polyline = MKGeodesicPolyline(coordinates: routeCoordinates, count: routeCoordinates.count)
polyline.title = "flight"
self.polylineFlight = polyline;
self.previousLatitude = latitude
self.previousLongitude = longitude
if appSingleton.mapView != nil {appSingleton.mapView.add(polyline)}
let polylineFlightDataSave = NSKeyedArchiver.archivedData(withRootObject: self.polylineFlight )
defaultsLoad.set(polylineFlightDataSave, forKey: "PolylineFlightData")
}
}
}
}
}
The problem is that whenever I switch to another tab, the current polyline disappears and a new one begins being drawn. I would like to save the polyline as a NSData using UserDefaults. However, this is not possible since it crashes on line 57 with uncaught exception of type NSException. Is there a way to save a polyline to preserve it after switching tabs?
Thanks a lot!