kka41
kka41

Reputation: 89

Saving an array in Swift

I am trying to save an array to the documents directory but the save function fails. I can tell this because it returns a value of false and when I try to read the array back I get nil.

I have included some code below I have written this with some various debug statements just trying to get it to work so sorry if ic seems a little weired.

@IBAction func Save(_ sender: Any) {

    var values = [jpyTextField.text,eurTextField.text]
    var answer: Bool

    let manager = FileManager.default
    let documents = manager.urls(for: .documentDirectory, in: .userDomainMask)
    let docURL = documents.first

    answer = (values as NSArray).write(to:docURL! , atomically: true)

    let readData = NSMutableArray (contentsOf: docURL!)

    print (docURL)
    print (readData?[0])
    print (answer)
}

Here is what I get back

file:///Users/kka/Library/Developer/CoreSimulator/Devices/82C6DEF6-20D0-4BB0-875A-C80D4AE9A4BD/data/Containers/Data/Application/F54CBC83-6756-466F-8701-E728F5C6DBF1/Documents/
nil
false

Upvotes: 0

Views: 293

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You need to specify a file name

let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! 
let fileURL = dir.appendingPathComponent("file.txt")
// write to fileURL 

Upvotes: 3

Related Questions