iOS 17 Directory Handling and File I/O in Swift – A Worked Example

In the Working with Directories in Swift on iOS 17 and Working with Files in Swift on iOS 17 chapters of this book, we discussed in detail the steps involved in working with the iOS file system in terms of both file and directory handling from within iOS apps. The goal of this chapter is to put theory into practice by working through the creation of a simple app that demonstrates some of the key concepts outlined in the preceding chapters.

The Example App

The steps in this chapter involve creating an iOS app consisting of a text field and a button. When the user touches the button after entering text into the text field, that text is saved to a file. The next time the app has launched, the file’s content is read by the app and pre-loaded into the text field.

Setting up the App Project

The first step in creating the app is to set up a new project. Begin by launching Xcode and creating a new project using the iOS App template with the Swift and Storyboard options selected, entering FileExample as the product name.

Designing the User Interface

The example app will consist of a button and a text field. To begin the user interface design process, select the Main.storyboard file to load it into the Interface Builder environment. Next, drag a Button and then a Text Field from the Library onto the view. Double-click on the button and change the text to Save. Position the components and resize the width of the text field so that the layout appears as illustrated in Figure 38-1:

Figure 38-1

Using the Resolve Auto Layout Issues menu, select the Reset to Suggested Constraints option listed under All Views in View Controller.


You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print


Select the Text Field object in the view canvas, display the Assistant Editor panel and verify that the editor is displaying the contents of the ViewController.swift file. Ctrl-click on the text field object and drag it to a position just below the class declaration line in the Assistant Editor. Release the line, and in the resulting connection dialog, establish an outlet connection named textBox.

Ctrl-click on the button object and drag the line to the area immediately beneath the viewDidLoad method in the Assistant Editor panel. Release the line and, within the resulting connection dialog, establish an Action method on the Touch Up Inside event configured to call a method named saveText.

Checking the Data File on App Startup

Each time the user launches the app, it will need to check to see if the data file exists (if the user has not previously saved any text, the file will not have been created). If the file exists, the contents need to be read by the app and displayed within the text field. An excellent place to put initialization code of this nature is in a method to be called from the viewDidLoad method of the view controller. With this in mind, select the ViewController. swift file, declare some variables that will be needed in the code and scroll down to the viewDidLoad method and edit the file as follows:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textBox: UITextField!
    var fileMgr: FileManager = FileManager.default
    var docsDir: String?
    var dataFile: String = ""

    override func viewDidLoad() {

    func checkFile() {
        let dirPaths = fileMgr.urls(for: .documentDirectory,
                                    in: .userDomainMask)
        dataFile =
        if fileMgr.fileExists(atPath: dataFile) {
            if let databuffer = fileMgr.contents(atPath: dataFile) {
                let datastring = NSString(data: databuffer,
                              encoding: String.Encoding.utf8.rawValue)
                textBox.text = datastring as String?
.Code language: Swift (swift)

Before proceeding, we need to take some time to talk about what the above code is doing. First, we declare some variables that will be used in the method and create an instance of the FileManager class. Because each iOS app on a device has its own Documents directory, we next make the appropriate calls to identify the path to that directory. Once we know where the documents directory is located, we construct the full path to our file (named datafile.dat) before checking whether the file exists. If it exists, we read the file’s contents and assign it to the text property of our text field object so that it is visible to the user. Now that we have the initialization code implemented, we need to write the code for our action method.

Implementing the Action Method

When the user enters text into our text field component and touches the save button, the text needs to be saved to the datafile.dat file in the app’s Documents directory. We need to implement the code in our saveText action method to make this happen. Select the ViewController.swift file if it is not already open and modify the template saveText method we created previously so that it reads as follows:


You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print


@IBAction func saveText(_ sender: Any) {

    if let text = textBox?.text {
        let dataBuffer = String.Encoding.utf8)
        fileMgr.createFile(atPath: dataFile, contents: dataBuffer,
                           attributes: nil)
}Code language: Swift (swift)

This code converts the text in the text field object and assigns it to a Data object, the contents of which are written to the data file by calling the createFile(atPath:) method of the file manager object.

Building and Running the Example

Once the appropriate code changes have been made, test the app by clicking on the run button located in the toolbar of the main Xcode project window.

When the app has loaded, enter some text into the text field and click on the Save button. Next, stop the app by clicking on the stop button in the Xcode toolbar and then restart the app by clicking the run button again. On loading for a second time, the text field will be primed with the text saved during the previous session:

Figure 38-2


This chapter has demonstrated the use of the iOS FileManager class to read and write data to the file system of the local device. Now that the basics of working with local files have been covered, the following chapters will introduce cloud-based storage.