Open your app's Documents folder programmatically in Files app

There is a scheme to launch the iOS Files app inside your app directory quickly.

Published: Feb. 13, 2022
App Store

While adding the gallery feature to SwitchBuddy, I implemented a way to open the app's Document folder in the built-in Files app. If you know the proper URL scheme, it is just one line of code.

Prerequisite

Also note, that there is a prerequisite. You need to make this directory "public" so it shows on its own in the "On my iPhone" section in Files app. This requires Info.plist modification, and I already have a blog post about that. Check it out to enable this for your app.

How to open Files app

Once you have enabled the public Documents folder, you need to construct a particular URL and use the UIApplication shared object to open it.

let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

if let sharedUrl = URL(string: "shareddocuments://\(documentsUrl.path)") {
    if UIApplication.shared.canOpenURL(sharedUrl) {
        UIApplication.shared.open(url, options: [:])
    }
}

The first line is pretty standard in the iOS development world. But to open the URL via Files, you need to add the shareddocuments:// prefix to it. The code above should open the Files app, assuming the user hasn't deleted it.

Using this approach, you can also navigate to folders inside your app's Documents folder.

Usages?

While this is a pretty niche topic, there are some solid use cases when to enable it. For example, I didn't want to build proper files management for the images in the gallery - because my app is not a files manager. So with this approach, I can let them delete, move, duplicate and do whatever with the files with just a few lines of code and some configuration.

Or perhaps if you are letting the user export files for backup, it may make more sense to save them to this public Documents directory where they can easily backup them in a single go instead of showing a share sheet.

Another option might be to use this for quick debugging of file operations.

Filip Němeček profile photo

WRITTEN BY

Filip Němeček @nemecek_f@iosdev.space

iOS blogger and developer with interest in Python/Django. Want to see most recent projects? 👀

iOS blogger and developer with interest in Python/Django. Want to see most recent projects? 👀