Search code examples
iosswiftencryptionnsfilemanagerfile-manager

iOS: Is there a way to export a file so that only the related App can read/write it?


my project is written in swift/swiftui latest version. Right now the user can export any file to the default folder (Files).

My Question: Is it possible to encrypt/protect the exported file in a way, so that only the app itself can read/write it again?

Does Swift support this kind of feature? Or do I have to implement a workaround for that?

Thx! for helping out!


Solution

  • If you don't want anyone else to see the file, don't export to Documents. Put it in Application Support or similar. You are sandboxed, so you are protected from anyone else ever seeing the file.

    If the goal is also to prevent the file from ever being backed up, then you can add instructions to that effect. Suppose you have the file's URL as myFileURL. Then (supplying mentally the surrounding do...catch blocks):

    var rv = URLResourceValues()
    rv.isExcludedFromBackup = true
    try myFileURL.setResourceValues(rv)
    

    Finally, if the goal is to encrypt a piece of data, not really a file per se, then put it in the user's keychain.