Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create text file for writing

Tags:

file

swift

I've a problem to write text in a file. What I've done so far is the following: I have a string with the text to store and the file name also as a string.

let someText = "abcd"
let fileName = "file:///xxx"

Of course "xxx" is a .txt file under the document directory so it should be possible to write.
Then I found out that I can use the write method o the string. But for this call I need the file name as url so I have this piece of code:

let fileUrl = URL(string: fileName)
do {
    try someText.write(to: fileUrl, atomically: false, encoding: String.Encoding.utf8)
}
catch { }

If I start my app then I will get an error "The file xxx does not exist". Ok that's correct because the file is not created. I thought that the write method does it automatically but it seems not so.
And that's the point I don't know how to solve this issue!

I'm using Xcode 8 + Swift 3.

+++ EDIT +++

I try to explain what I'm exactly looking for.
Let's say I've two tasks: The first task builds file names and stores it in a database. That's why I work with strings:

var fileName = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).path
if (!fileName.hasSuffix("/")) {
    fileName += "/"
}
fileName += "file.txt"

As you can see the file is not created at this moment because I only need the name in this task.

Ok and then the second task. It has to select a specific file name from the database and append it with the file:// scheme:

let fileName = "file://" + fileNameFromDatabase

Then the text is written with the code above.
It's clear that the file not exists in this task because I only have the name. That's why I think that the error message of the write method is correct.
What I'm now looking for is a possibility to create the file/write the text in one step.

like image 433
altralaser Avatar asked Oct 12 '16 20:10

altralaser


1 Answers

Swift 3 example:

func write(text: String, to fileNamed: String, folder: String = "SavedFiles") {
    guard let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { return }
    guard let writePath = NSURL(fileURLWithPath: path).appendingPathComponent(folder) else { return }
    try? FileManager.default.createDirectory(atPath: writePath.path, withIntermediateDirectories: true)
    let file = writePath.appendingPathComponent(fileNamed + ".txt")
    try? text.write(to: file, atomically: false, encoding: String.Encoding.utf8)
}
like image 71
Bogdan Novikov Avatar answered Oct 07 '22 06:10

Bogdan Novikov