Text File Workshop: Write Text File

Today you will add code in the SaveFileViewController.swift file to implement the write text file operation in the SaveFileViewController class. The app user is the one who will initiate this text file operation by entering a note in the Save File view’s textView and tapping the Save button.

The User Interaction Table

Here is a snap shot of the Save File view and a User Interaction table of how the app user will use the view to write (save) a text file to the application sandbox’s Documents folder.

User Action App Response
The user enter text in the textView and tap the Save File button

niftytextfile-part1-5

The app respond by doing the following:

  • Validate the textView
  • Create a text file
  • Dump the user’s note in the file
  • Save the file in the app’s Documents folder
  • Clear out the textView
  • Dismiss the keyboard
  • Display a message in an alert view

reminder2Above table shows a high-level view of how the user will use the Save File view to perform a specific action. In this case it is this: write a text file to the app’s sandbox.

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.

The User Launch The App

Before the user sees the Save File view, you’ll have to add code in the SaveFileViewController.swift file to perform these tasks:

  • Print the sandbox’s Documents directory path in the console
  • Clear out the textView
  • Dismiss the keyboard when the user tap the Save File view’s background

Here’s the code to implement above tasks in the class file. By the way, the print statement not required. It is only for debugging purpose.

override func viewDidLoad() {
  super.viewDidLoad()
        
  // Clear out the textView
  textView.text = nil

 // Print the sandbox's Documents directory path in the console.
 print(File.getDocumentsDirectory())
}

// This function create and show a message in an alert view object
func showAlertView(title: String, msg: String) {
  let alert = UIAlertController(title: title, message: msg, preferredStyle: .Alert)
  let cancelAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
  alert.addAction(cancelAction)
  presentViewController(alert, animated: true, completion: nil)
}
    
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
  // Dismiss the keyboard when the view's background is touched
  textView.resignFirstResponder()
}

The Write Text File Code

Here’s the code to add in the SaveFileViewController, to implement the write text file operation.

var File = TexFileManager()

@IBAction func saveButtonPressed(sender: UIButton) {
  // Dismiss the keyboard
  textView.resignFirstResponder()

  // Validate the textView and display a message in an alert view
  if textView.text.isEmpty {
    showAlertView("Your Note", msg: "It is required")
  } else {
    // Create a unique text file
    let fileName = File.createTextFileName()
            
    // Dump the textView's data in the text file and
    // Write the text file to the Documents directory
    File.writeFile(fileName, data: textView!.text)
            
    // Clear out the textView
    textView.text = nil
            
    // Display a message in an alert view
    showAlertView("Your Note", msg: "It was save in a file called, \(fileName)") 
}

The Keyboard is Blocking The TextView

When the user is editing the textView, the keyboard may block the line she is currently editing. To fix this problem you have to add code in the SaveFileViewController class to shift the textView’s text up so the line the user is currently editing appear above the keyboard. To implement this feature in the SaveFileViewController class, you have to add this code in the ViewDidLoad() function.

NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyboardDidShow:", name:UIKeyboardDidShowNotification, object: nil)

Every time the keyboard is shown on screen, the device sends various notifications to the app regarding each state of the keyboard. So code shown above notify the app when the keyboard did show on the device’s screen, via the UIKeyboardDidShowNotification observer.

The keyboardDidShow() function is fired every time the app user tap the Text View. Here is the code to implement it in the SaveFileViewController class. Add it below the touchesBegan() function.

func keyboardDidShow(notification: NSNotification) {
  let info: Dictionary = notification.userInfo!
  var keyboardSize: CGSize!
 
  if let aValue = info[UIKeyboardFrameBeginUserInfoKey] as? NSValue {
    keyboardSize = aValue.CGRectValue().size
  }
        
  let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height - 22, 0.0)
  textView.contentInset = contentInsets
  textView.scrollIndicatorInsets = contentInsets
}

Test The Save File Button Code

You entered code in the SaveFileViewController.swift file to write the selected text file to the app’s Documents folder. Also, you entered code in the SaveFileViewController.swift file to fix the keyboard problem.

Now, run the app on your real device or the Simulator and use the Save File View to write one or several notes in the app’s Documents folder.

niftytextfile-part1-5 niftytextfile-part1-6

Notice that as soon, as the Save File View appear on the device’s screen, the full path to the Documents folder is printed in Xcode’s Debugger console. Copy and past it in Finder’s Go to Folder window’s input box and click the Go button.

finder-goto

Finder display the application sandbox’s Documents folder and you should see your text file/files there.

niftytextfile-part1-7

That’s it. Now you know how to write (save) one or more text files to the app’s Documents folder and use Finder to see if the app really wrote your text files to the Documents folder.

next-iconNext week, you will implement the Read directory text file operation, in the NiftyTextFile project. Until then comments are welcomed. 🙂