Swift Tip – Accessing a User’s Documents Directory with URL Extension

When you need to access the documents directory on a user’s device, what do you do?

In the past, I know I’ve gotten used to typing out the same set of code over and over throughout my apps. I know, I know – DRY – don’t repeat yourself.

One way to simplify this is to use a Swift extension to URL. Doing this will help you centralize where this code is located in your app, and keep your code DRY. If you need to access the documents directory in more than one spot, you’re just a URL property call away from it.

Extension implementation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
extension URL {
    static var documentsURL: URL {
        return try! FileManager
            .default
            .url(for: .documentDirectory, 
                 in: .userDomainMask, 
                 appropriateFor: nil, 
                 create: true)
    }
}

Extension usage

Here’s an example of using the extension during the routine to create the Core Data stack. For that process, you need to grab a URL to where your SQLite database file will be located. Take a look:

1
2
3
4
5
// ...

let storeURL = URL.documentsURL.appendingPathComponent("AppDatabase.sqlite")

// use the URL
You could be needing to access the directory for saving files or retrieving files totally unrelated to Core Data. No matter what you’re doing, being able to write URL.documentsURL is pretty convenient!

comments powered by Disqus