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

From Techotopia
Jump to: navigation, search

PreviousTable of ContentsNext
Working with Files in Swift on iOS 8Preparing an iOS 10 App to use iCloud Storage


You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book


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




The Example Application

The steps in this chapter walk through the creation of an iOS 10 application 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 application is launched the content of the file is read by the application and pre-loaded into the text field.

Setting up the Application Project

The first step in creating the application is to set up a new project. To do so, start the Xcode environment and select the option to create a new project (or select the File -> New -> Project menu option if Xcode is already running or the welcome screen does not appear by default).

Select the Single View Application template, choose the Universal option from the Devices menu, Swift as the language and name the product FileExample.


Designing the User Interface

The example application is going to 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. Drag a Button and then a Text Field from the Object Library panel (View -> Utilities -> Show Object 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:


The user interface layout for an iOS file handling example app

Figure 38-1


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

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 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.

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

Checking the Data File on Application Startup

Each time the application is launched by the user it will need to check to see if the data file already exists (if the user has not previously saved any text, the file will not have been created). If the file does exist, the contents need to be read by the application and displayed within the text field. A good place to put initialization code of this nature is in 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 it 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() {
        super.viewDidLoad()

        let filemgr = FileManager.default

        let dirPaths = filemgr.urls(for: .documentDirectory,
                                    in: .userDomainMask)

        dataFile = 
		dirPaths[0].appendingPathComponent("datafile.dat").path

        if fileMgr.fileExists(atPath: dataFile!) {
            let databuffer = fileMgr.contents(atPath: dataFile!)
            let datastring = NSString(data: databuffer!,
                                       encoding: String.Encoding.utf8.rawValue)
            textBox.text = datastring as? String
        }
    }
.
.
.

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

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 application 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 (which is named datafile.dat) before checking whether the file already exists. If it exists, we read the contents of the file 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 located in the application’s Documents directory. In order to make this happen we need, therefore, to implement the code in our saveText action method. 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:

@IBAction func saveText(_ sender: AnyObject) {
    let databuffer =
          (textBox.text)!.data(using: String.Encoding.utf8)

    fileMgr.createFile(atPath: dataFile!, contents: databuffer,
                                    attributes: nil)
}

This code converts the text contained 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 application by clicking on the run button located in the toolbar of the main Xcode project window.

When the application 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:


Ios 8 file example app running.png

Figure 38-2


You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book



PreviousTable of ContentsNext
Working with Files in Swift on iOS 8Preparing an iOS 10 App to use iCloud Storage