Text File Workshop: Introduction

In this Text File Workshop series you will learn the basics of working with text files and folders in an iOS project you will create, design, and code from scratch.

Code presented on this page assume you are using Xcode 7.0 and Swift version 2.0. So if you are using a older or newer version of Swift, it may produce errors. Fix them by using Xcode’s Fix-it tool. Also, I assume you aren’t a newbie to the Swift Programming Language and you know your way around Xcode Integrated Development Editor.

Text File and Folders

A text file is a document that contain only text. A text file has no special formatting such as bold text, italic text, images, etc. Once created, you can add, edit, and delete a text file. It is common programming practice to give a text file the extension .dat or .txt.

text-file

Text files are stored in a container called a folder. If you had thousands of paper files on your desk, it would be nearly impossible to find any particular file when you needed it. That’s why people often store paper files in folders inside a filing cabinet.

folder-filing-cabinet

On your Mac and your iOS app, folders work the same way. Folders can also store other folders and files. A folder within a folder is usually called a subfolder. You can create any number of subfolders, and each can hold any number of files and additional subfolders.

folders

When you create an iOS application the Operating System automatically create three folders in the Application Sandbox. One of them is called Documents and that’s where you should store your iOS application’s text files. You can even create subfolders within the Documents folder and store text files in them too.

sandbox-folders

Overview of The Workshop Lessons

Over the next seven weeks, you will implement these text file operations in a NiftyTextFile project you create today.

1. Write text file
2. Read directory
3. Read text file
4. Update text file
5. Delete text file
6. Find text file
7. Subfolder operations
➤ Create subfolder
➤ Move a text file to a subfolder
➤ Move text file from a subfolder
➤ Delete a text file from a subfolder
➤ Change a button image programmatically

Create and Design a Single View Application

To learn the basics of working with text files and folders in this tutorial series, create a new iOS project (⌘ + Shift + N). When prompted, select the “Single View Application” template and configure the project options window as shown in the image below. When prompted, save the project in the Interactive Swift Programming folder on your Mac.

niftytextfile-part1-0

Once the project is loaded in the workspace, change the name of the viewController.swift file to SaveFileViewController.swift.

niftytextfile-part1-1

In the Identity inspector, reconnect the class to the storyboard scene.

niftytextfile-part1-2

Modify the Save File View Controller scene by adding a Label, a TextView and a Button object on its canvas. Modify the Label and Button so they look like the image shown below. Next, use the Assistant Editor to create the IBOutlet property variables and the IBAction function shown in the image below. Don’t forget to “Add Missing Constraints” to the scene’s object and create the File variable shown in the image as well.

niftytextfile-part1-3

Create a TextFileManager Class

Since you will be performing various text file operations in the NiftyTextFile project, you have to create a new class file (⌘ + N) with these options:

niftytextfile-part1-4

Add Code in The TextFileManager Class

As the tutorial progress you will add functions in the TextFileManager class file to perform text file operations. Here’s the source code to implement five of them:

// This function fetch and return the full path to the sandbox's Documents folder
func getDocumentsDirectory() -> String {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths.first!
    return documentsDirectory
}

// This function write a text file to the Documents folder
func writeFile(fileName: String, data: String) {
    let documentsDir = getDocumentsDirectory().stringByAppendingString("/"+fileName)
    do {
       try data.writeToFile(documentsDir, atomically: true, encoding: NSUTF8StringEncoding)
    } catch let writeError as NSError {
        print("File Write Error:\n\(writeError)")
    }
}

// This function create and return a uniquie text file name
func createTextFileName() -> String {
    let fileName = getTodaysDate() + " " + randomString() + ".txt"
    return fileName
}

// This function fetch and return today's date
func getTodaysDate() -> String {
    let todaysDate:NSDate = NSDate()
    let dateFormatter:NSDateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
    let stringDateAndTime:String = dateFormatter.stringFromDate(todaysDate)
    let chunk = stringDateAndTime.componentsSeparatedByString(" ")
    return chunk[0]
}

// This function create and return a random string that contain four characters
func randomString() -> String {
    let len: Int = 4
    let needle : NSString = "ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz123456789"
    let randomString : NSMutableString = NSMutableString(capacity: len)
    
    for (var i=0; i < len; i++){
        let length = UInt32 (needle.length)
        let rand = arc4random_uniform(length)
        randomString.appendFormat("%C", needle.characterAtIndex(Int(rand)))
    }
    
    return randomString as String
}

What’s Next

next-iconThat’s all for today. Next week, you will implement the write a text file operation, in the NiftyTextFile project. Until then, comments are welcomed. 🙂