Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save/load files in app with Swift 4 [duplicate]

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.

like image 462
Zelota91 Avatar asked Jan 22 '18 17:01

Zelota91


1 Answers

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)")
}
like image 171
SafeFastExpressive Avatar answered Oct 15 '22 17:10

SafeFastExpressive