Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to locally save an array in swift [duplicate]

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.

like image 869
Charles Zhang Avatar asked Sep 01 '25 16:09

Charles Zhang


1 Answers

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)
}
like image 117
Leo Dabus Avatar answered Sep 06 '25 14:09

Leo Dabus