0

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
1
  • hi there! your docURL is a path to the directory. You need to add path components such as file name and file extension. However. I think it would be best for you to save it from the data method. d.write(to: URL(fileURLWithPath: filePath)) where d is your array represented as data. Commented May 30, 2019 at 1:17

1 Answer 1

3

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 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.