7

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.

Gereon
  • 17,258
  • 4
  • 42
  • 73
Zelota91
  • 71
  • 1
  • 1
  • 2

1 Answers1

9

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)")
}
SafeFastExpressive
  • 3,637
  • 2
  • 32
  • 39