Save/load files in app with Swift 4

Zelota91 picture Zelota91 · Jan 22, 2018 · Viewed 9.1k times · Source

my app needs to create files (e.g. .txt files) and directory to catalogue that file, that have to be stored in the phone. Running the app, I would create a specific directory, and a specific .txt file that will be saved internally.

I come from Android Studio and it's quite simple to do that, but here on Swift I can't find a way.

I try with this:

// Save data to file
let fileName = "Test"
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")

and the file is available if the app creates it when it starts.

If I comment those lines and check for the existance of that file, it fails.

Any suggestion? I think I'm using the wrong classes, but I can't find anything else.

Answer

SafeFastExpressive picture SafeFastExpressive · Jan 22, 2018

You need to actually write the file.

import UIKit

let fileName = "Test"
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")

let text = "my text for my text file"
do {
    try text.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
    print("failed with error: \(error)")
}

do {
    let text2 = try String(contentsOf: fileURL, encoding: .utf8)
    print("Read back text: \(text2)")
}
catch {
    print("failed with error: \(error)")
}