4

How do I locally save an array in swift? I have an array in my app and everytime it displays 1 random string to the user. When the string has been displayed, it is deleted from the array. My problem is, when ever the user exists the app and relaunch it, my array starts over again; I can't get back the array that was before the user exited the app.

Charles Zhang
  • 109
  • 1
  • 12

1 Answers1

4

edit/update:

let strings = ["abc", "def", "ghi"]
do {
    let documentsDirectory = try FileManager.default.url(for: .documentDirectory,
                                                         in: .userDomainMask,
                                                         appropriateFor: nil,
                                                         create: true)
    let fileURL = documentsDirectory.appendingPathComponent("array.plist")
    // Saving to disk
    try NSKeyedArchiver.archivedData(withRootObject: strings,
                                     requiringSecureCoding: false)
    .write(to: fileURL,
           options: .atomic)
    print("successfully saved to file url", fileURL.path)
    
    // Loading from disk
    if let loadedArray = try NSKeyedUnarchiver
        .unarchiveTopLevelObjectWithData(Data(contentsOf: fileURL)) as? [String] {
        print("loadedArray:", loadedArray) // "[abc, def, ghi]"
    }
} catch {
    print(error)
}

or if you would like to use UserDefaults (note that UserDefaults it is not meant for saving your app data, it should only be used to preserve your app settings/state):

UserDefaults.standard.set(array, forKey: "array")

if let loadedArray = UserDefaults.standard.stringArray(forKey: "myarray") {
    print(loadedArray)
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571