0

I have successfully created an array of dictionaries that I thought was a final solution for my question (here: Store CLLocation Manager Values in Device swift) and here is the code I came up with:

func arrayOfDictionaries() {
    var offline:[[String:AnyObject]] = []
    offline.append(["LATITUDE: ": userLocation.coordinate.latitude, "LONGITUDE: ": userLocation.coordinate.longitude, "SPEED: ": userLocation.speed])

    NSUserDefaults().setObject(offline, forKey: "offLine")

    if let offLinePositions = NSUserDefaults().arrayForKey("offLine") as? [[String:AnyObject]] {
        //print(offLinePositions)


        for item in offLinePositions {
            print(item["LATITUDE: "]! as! NSNumber)  // A, B
            print(item["LONGITUDE: "]! as! NSNumber)  // 19.99, 4.99
            print(item["SPEED: "]! as! NSNumber)  // 1, 2
        }
    }

}

But when I tested the app, I realized that I only have 1 position stored in the array. So my thought is to create another array and insert the values from the first one. How can I do that?

Cœur
  • 37,241
  • 25
  • 195
  • 267
ggirao
  • 13
  • 5

1 Answers1

0

You're creating offline array, appending one item to it and then overwriting the offLine array in the user defaults with this . That's why you only have one item in it.

First you need to try to grab the existing array from the user defaults then append another item to it and write it back to the user defaults:

func arrayOfDictionaries() {
    let defaults = NSUserDefaults.standardUserDefaults()
    var offline:[[String:AnyObject]]
    if defaults.arrayForKey("offLine") != nil {
        //Grab offLine array from user defaults
        offline = defaults.arrayForKey("offLine") as! [[String:AnyObject]]
    } else {
        //Setting the offLine array for the first time
        offline = []
    }
    offline.append(["LATITUDE: ": userLocation.coordinate.latitude, "LONGITUDE: ": userLocation.coordinate.longitude, "SPEED: ": userLocation.speed])

    defaults.setObject(offline, forKey: "offLine")

    if let offLinePositions = NSUserDefaults().arrayForKey("offLine") as? [[String:AnyObject]] {
        //print(offLinePositions)


        for item in offLinePositions {
            print(item["LATITUDE: "]! as! NSNumber)  // A, B
            print(item["LONGITUDE: "]! as! NSNumber)  // 19.99, 4.99
            print(item["SPEED: "]! as! NSNumber)  // 1, 2
        }
    }

}
Swifty
  • 3,730
  • 1
  • 18
  • 23
  • At first time worked. Than I add some 2 keys to the Array and crashed on that (first key added). So I remember that I wasn't reseting the defaults on viewDidLoad. WORKING perfect! – ggirao Oct 09 '16 at 16:19