6

I red the comments of this code example here:

https://www.hackingwithswift.com/example-code/strings/writetofile-how-to-save-a-string-to-a-file-on-disk

// failed to write file – bad permissions, bad filename, missing permissions, 
    or more likely it can't be converted to the encoding

I tried the code and it works on a device without requesting any permission. I couldn't find anything useful in the docs.

So, my question is: what permissions (bad or missing) is the author talking about? Do I need special permissions to write to the app documents directory?

2 Answers2

9

No, your app does not need special permissions as such, however scenarios do exist where the app might be unable to write to the file.

One example is if your app is using disk protection for its files, and you try to write to the folder when the disk is encrypted. Other examples are:

  1. The disk is full.
  2. The file is being written to by a different process (ie. you're downloading content to it in a background URLSession).
  3. The path contains some invalid character (e.g. ":").

If an error does occur, the cause can usually be determined by inspecting the error.

The comment seems to be intended a general placeholder indicating some of the possible causes for receiving an error when writing a file, so that if you were to use the code and you ran into an error condition, you would have some place to start.

The documentation is a good place to refer to when in doubt.

Luke Van In
  • 5,215
  • 2
  • 24
  • 45
  • 2
    @ian-bell It is worth noting that the *documents* directory on iOS is not a shared resource like on your Mac. Each app has its own sandboxed container with sub-directories it can write to - the documents directory is just one of them. Modifying files in these directories does not affect anything outside of your app. – Luke Van In Jul 12 '16 at 10:05
  • 1
    I noticed now you can create a shared folder between apps using App Group and referencing the folder through containerURLForSecurityApplicationGroupIdentifier –  Jul 12 '16 at 14:21
1

There is no special permission in iOS to write a file like android permission. In iOS we need permission only for accessing contacts from device & images from photo gallery. For more info to write file to secondary storage look at apple documentation.

Bhaskar
  • 51
  • 5