File Management Tutorial in iOS8 with Swift

When an iOS App is installed on a device, a folder structure will be created, including a tmp directory for storing temporary data. In this tutorial we are managing files in this tmp directory such as creating, reading and deleting files. This tutorial is built in iOS 8.1 with Xcode 6.1.

Open Xcode and create a new Single View Application. For product name, use IOS8SwiftFileManagementTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the Storyboard and drag four Buttons to the main View. Give the buttons the following titles. 

  • Create File
  • List Directory
  • View File Content
  • Delete File

The Storyboard will look like this.

Select all items by holding the Ctrl-key  and select the "Resolve Auto Layout Issues" button at the bottom-right(3rd button) and select Add Missing Constraints.

The buttons will be placed below and next to each other, even when the device rotates. Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the "Create File" Button to the ViewController class and create the following Action.

Ctrl and drag from the "List Directory" Button to the ViewController class and create the following Action.

Ctrl and drag from the "View File Content" Button to the ViewController class and create the following Action.

Ctrl and drag from the "Delete File" Button to the ViewController class and create the following Action.

Go to the ViewController.swift file and add the following properties to the ViewController class

var fileManager = NSFileManager()
var tmpDir = NSTemporaryDirectory()
let fileName = "sample.txt"
  • The NSFileManager class lets you examine the contents of the filesystem and make changes to it
  • The NSTemporaryDirectory is a temporary directory for the current user
  • A file with a filename of "sample.txt" will be used for this tutorial

Before the Action methods will be implemented a helper method  enumerateDirectory will be created, which will be used to check for files inside a directory.

func enumerateDirectory() -> String? {
    var error: NSError?
    let filesInDirectory =  fileManager.contentsOfDirectoryAtPath(tmpDir, error: &error) as? [String]
        
    if let files = filesInDirectory {
        if files.count > 0 {
            if files[0] == fileName {
                println("sample.txt found")
                return files[0]
            } else {
                println("File not found")
                return nil
            }
        }
    }
    return nil
}

All files inside the temporary directory will be put into a array of type String and this array will be checked for the existence of our sample.txt file. When succesful, the filename will be returned, otherwise nil will be returned. Next, implement the createFile method.

@IBAction func createFile(sender: AnyObject) {
    let path = tmpDir.stringByAppendingPathComponent(fileName)
    let contentsOfFile = "Sample Text"
    var error: NSError?
        
    // Write File
    if contentsOfFile.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: &error) == false {
        if let errorMessage = error {
            println("Failed to create file")
            println("\(errorMessage)")
        }
    } else {
        println("File sample.txt created at tmp directory")
    }
}

The sample.txt file is created with some content and written to the tmp directory with the writeToFile:atomically:encoding:error method. When this actions fails. an error message will be printed to the console. Next, implement the listDirectory method.

@IBAction func listDirectory(sender: AnyObject) {
    // List Content of Path
    let isFileInDir = enumerateDirectory() ?? "Empty"
    println("Contents of Directory =  \(isFileInDir)")
}

The enumerateDirectory method is called, when there is no file present in the directory the "Empty" string is assigned to the isFileInDir variable. the ?? operator is the nil coalescing operator which evaluates an expression (enumerateDirectory() ) When true the optional value will be unwrapped, when false a default value will be returned ( "Empty" string). The Contents of the directory will be printed to the console. Next, implement the viewFileContent method.

@IBAction func viewFileContent(sender: AnyObject) {
    let isFileInDir = enumerateDirectory() ?? ""
        
    let path = tmpDir.stringByAppendingPathComponent(isFileInDir)
    let contentsOfFile = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
        
    if let content = contentsOfFile {
        println("Content of file = \(content)")
    } else {
        println("No file found")
    }
}

The contentsOfFile:encoding:error method puts the content of a file into a NSString. If the file is present, the content will be printed to the console, otherwise the "No file found" message will be printed to the console. Finally, implement the deleteFile method

@IBAction func deleteFile(sender: AnyObject) {
    var error: NSError?
        
    if let isFileInDir = enumerateDirectory() {
        let path = tmpDir.stringByAppendingPathComponent(isFileInDir)
        fileManager.removeItemAtPath(path, error: &error)
    } else {
        println("No file found")
    }
}

The removeItemAtPath:error method deletes the file. Build and Run the project, select the  buttons and look at the console to see the results of each action.

You can download the source code of the IOS8SwiftFileManagementTutorial at the ioscreator repository on Github.