iosswiftpermissionsdocuments

Write file to documents directory and permissions


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?


Solution

  • 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.