Search code examples
arraysswift3mapkitnsuserdefaultsmapkitannotation

Saving Annotations on MapView


Currently the app I am developing creates custom annotations, but when the user switches away from the page with the mapView they are all unloaded. I am saving them into a custom array but UserDefaults is not letting me save that array. Is there an easy way to preserve placed annotations or how would I get UserDefaults to save my array. My array is like this:

var mapAnnotations = [pinLocations]()
struct pinLocations {
    let latitude: Double
    let longnitude: Double
    let name: Double
    let time: String
}

Solution

  • Make your struct a class instead, deriving from NSObject, and adopt NSCoding by implementing init?(coder:) and encode(with:). An array of this class can now be archived into an NSData and saved into UserDefaults by calling NSKeyedArchiver.archivedData(withRootObject:) (and the reverse by calling NSKeyedUnarchiver.unarchiveObject(with:)).