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.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
FileManager Class Tutorial for macOS: Getting Started with the File System
30 mins
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?
- It’s your old friend
FileManager
class to the rescue again. :] - The
FileManager
class has a method for returning a list of appropriateURLs
for specific uses. In this case, you are looking for theapplicationSupportDirectory
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. - As you did in the playground, append a path component to create an app-specific folder
URL
and check to see if it exists. - If the folder does not exist, try to create it and any intermediate folders along the path, returning
nil
if this fails. - Append another path component to create the full
URL
for the data file and return that.
.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.
Where to Go From Here?
You can download the final sample project here.
In this FileManager
class tutorial:
- You learned how
URLs
can represent local files and folders and can show many properties available to you about a file or folder. - You learned how you can add and remove path components to a
URL
. - You explored the
FileManager
class which gives you access properties likehomeDirectoryForCurrentUser
, theapplicationSupportDirectory
and evenattributesOfItem
with detailed information about a file or folder. - You learned how to save information to a file.
- 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!