Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create empty file swift

Tags:

How can I create an empty file in Swift code, preferably avoiding the Terminal, in as few lines of code as possible? I am using Swift 4, Xcode 9.4.1 and macOS High Sierra. I have tried using the Terminal to run Bash code, see my post here.

Edit:
The question this ones' been marked as duplicate for is for the terminal, which I am trying to avoid now, read that question (which I wrote) to see why.

Edit 2:
If the file already exists, I wish for the code to raise an error to the user, and the code will display it with NSTextField or UILabel.

Thanks in advance! 😅😅

like image 979
Benj Avatar asked Sep 10 '18 10:09

Benj


1 Answers

Using your script in the linked question, try:

shell("touch file.txt")

The command touch will create the file file.txt.

You do not need the terminal for anything here, just run your .swift file and you will have your file.

In case you need the file to write to, just use something like this:

let url = URL(fileURLWithPath: "file.txt")
try "Some string".write(to: url, atomically: true, encoding: .utf8)

You file file.txt will contain the string "Some string" in it.

Update

AFAIK it is not possible to just create a file, but you could create a file with an empty string:

try "".write(to: url, atomically: true, encoding: .utf8)

As mentioned by OP in comment, it is also necessary to disable sandboxing: Remove Sandboxing

like image 184
regina_fallangi Avatar answered Sep 28 '22 18:09

regina_fallangi