I have a problem with writing text to a file. What I have done so far is this: I have a line with saved text and a file name as well as a line.
let someText = "abcd" let fileName = "file:///xxx"
Of course, "xxx" is a .txt file in the document directory, so it could be written.
Then I found out that I can use the o write method for 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 run the application, I will get the error message "The xxx file does not exist." Itโs good that this is correct, because the file was not created. I thought the recording method does this automatically, but it is not. And this moment I do not know how to solve this problem!
I am using Xcode 8 + Swift 3.
+++ EDIT +++
I'm trying to explain what I'm exactly looking for. Let's say I have two tasks: the first task builds the file names and stores them in the database. Therefore, 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 being created at the moment, because I only need a name in this task.
Good, and then the second task. He should select a specific file name from the database and add it to the file: // schema:
let fileName = "file://" + fileNameFromDatabase
Then the text is written using the code above.
It is clear that the file does not exist in this task because I only have a name. Therefore, I believe that the write method error message is correct. Now I'm looking for an opportunity to create a file / write text in one step.