2

How do you go about creating files at arbitrary locations given you have the absolute path? I want to create a file in some arbitrary location /Users/me/random/project3/<moreStuffInThePath. How would I go about doing this?

To create a directory I would do:

try FileManager.default.createDirectory(atPath: "/Users/me/random/project3/<directoryName>"

This worked fine for directories.

However the counterpart for creating files does not work:

FileManager.default.createFile(atPath: "Users/me/random/project3/something.txt", contents: someString.data(using: .utf8)) // always returns false

I have checked out other stack overflow threads on creating files. Everything I found was about creating files in the .documentDirectory or it was outdated.

Eg: How to create text file for writing

Create empty file swift

Read and write a String from text file

TLDR: How do I create text files/files with random extensions at arbitrary locations on the pc given I have the absolute path?

I would also be grateful if someone could explain why all tutorials available on this matter are about the document directory. Why is it so significant?

Thank you!

ravas
  • 31
  • 3

1 Answers1

1

This is most likely because your app is sandboxed.

Go to your project settings, select the macOS target and go to "Signing and Capabilities". You should see something like this:

enter image description here

If your app needs to create files in arbitrary locations, you must remove the app sandbox by clicking on the "x" on the top right. Note that this will cause your app to be rejected from the Mac App Store.

If you want to upload your app to the Mac App Store, then you must keep the sandbox, and write to "user selected locations" only. Select "Read/Write" rather than "Read Only" next to "User Selected File". (Although it says "File", this includes directories too) This allows you to write to locations chosen by a user using something like an NSSavePanel.

Sweeper
  • 213,210
  • 22
  • 193
  • 313