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

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

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// ...
3let storeURL = URL.documentsURL.appendingPathComponent("AppDatabase.sqlite")
5// 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