FileManager Class Tutorial for macOS: Getting Started with the File System

In this tutorial, learn to use the FileManager class in a macOS app. Work with files, folders and navigate the file system while creating a working app. By Sarah Reichelt.

3.5 (11) · 2 Reviews

Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Contents

Hide contents

Saving App State

Normally, I would store app-state data in UserDefaults, which is saved automatically for you in the Preferences folder. But that doesn't allow you to do anything fancy with the file system. Instead, you will save this data to a dedicated app folder inside the Application Support folder.

Scroll down to the end of ViewController.swift and you’ll see an extension dedicated to saving and restoring the user's selections.

I’ve provided the functions that do the actual writing and reading. Writing uses the same write(to:atomically:encoding) method used when saving the info file. Reading uses a String initializer to create a String from a URL.

The really interesting thing here is how to decide where to save the data. You’ll do that in urlForDataStorage, which is returning nil at the moment.

Replace urlForDataStorage with the following:

private func urlForDataStorage() -> URL? {
  // 1
  let fileManager = FileManager.default

  // 2
  guard let folder = fileManager.urls(for: .applicationSupportDirectory,
                                      in: .userDomainMask).first else {
                                        return nil
  }

  // 3
  let appFolder = folder.appendingPathComponent("FileSpy")
  var isDirectory: ObjCBool = false
  let folderExists = fileManager.fileExists(atPath: appFolder.path, 
  			                    isDirectory: &isDirectory)
  if !folderExists || !isDirectory.boolValue {
    do {
      // 4
      try fileManager.createDirectory(at: appFolder,
                                      withIntermediateDirectories: true,
                                      attributes: nil)
    } catch {
      return nil
    }
  }

  // 5
  let dataFileUrl = appFolder.appendingPathComponent("StoredState.txt")
  return dataFileUrl
}

What is all this code doing?

  1. It’s your old friend FileManager class to the rescue again. :]
  2. The FileManager class has a method for returning a list of appropriate URLs for specific uses. In this case, you are looking for the applicationSupportDirectory in the current user's directory. It is unlikely to return more than one URL, but you only want to take the first one. You can use this method with different parameters to locate many different folders.
  3. As you did in the playground, append a path component to create an app-specific folder URL and check to see if it exists.
  4. If the folder does not exist, try to create it and any intermediate folders along the path, returning nil if this fails.
  5. Append another path component to create the full URL for the data file and return that.
Note: .applicationSupportDirectory is a short way to say FileManager.SearchPathDirectory.applicationSupportDirectory. .userDomainMask refers to FileManager.SearchPathDomainMask.userDomainMask. While the shorthand is much easier to type and read, it is useful to know where these come from, so you can find them in the documentation if you ever need to look them up.

Build and run, select a folder, then click on a folder or file. Use the Quit menu item or Command-Q to close the app. Don’t quit via Xcode, or the lifecycle methods won’t trigger a save. Run the app again and notice it opens up to the file or folder you were viewing when you quit.

Saved App State

Note: If you want to see the stored-state data file, hold down Option while clicking on Finder's Go menu and select Library. In the new Finder window, open Application Support and look for the FileSpy folder. You should see the StoredState.txt file with your selected folder and item.

Where to Go From Here?

You can download the final sample project here.

In this FileManager class tutorial:

  1. You learned how URLs can represent local files and folders and can show many properties available to you about a file or folder.
  2. You learned how you can add and remove path components to a URL.
  3. You explored the FileManager class which gives you access properties like homeDirectoryForCurrentUser, the applicationSupportDirectory and even attributesOfItem with detailed information about a file or folder.
  4. You learned how to save information to a file.
  5. You learned how to check if a file or folder exists.

For more information, check out Apple's FileManager API Reference Documentation which shows many more of the available methods in the FileManager class.

You are now ready to begin incorporating the use of files and folders in your own apps.

If you have any questions or comments please join the forum discussion below!