Passing text from text file to UITextView in "Swift 3"

Viewed 3508

I'm a beginner in iOS development and I am trying to make a simple app which Passing text from text file to UITextView in "Swift 3". I have looked up many tutorials on YouTube, stack and other websites, but all of them seem to either give me a lot of errors or are too hard for me too understand (as I am too unexperienced).

Screenshot of Storyboard

There are three buttons, and three text files, and one text view. When user clicks on the first button, file1 will be loaded into the text field.

Some of my attempts, it's give me error on txt_view.text = txt1.txt

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var txt_view: UITextView!

    @IBAction func btn_txt1(_ sender: Any) {

        txt_view.text = txt1.txt
    }

    @IBAction func btn_txt2(_ sender: Any) {

        txt_view.text = txt2.txt
    }

    @IBAction func btn_txt3(_ sender: Any) {

        txt_view.text = txt3.txt
    }

    override func viewDidLoad(){
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning(){
        super.didReceiveMemoryWarning()
    }
}
5 Answers

Following is the way to load the text file in the text view.

Swift 4.x

func loadFileContent(_ fileName: String) {
if let path = Bundle.main.path(forResource: fileName,
                               ofType: "txt") {
  do {
    let text = try String(contentsOfFile: path, encoding: .ascii)
    openSourceTextView.text = text
  } catch let error {
    debugPrint(" Error - \(error.localizedDescription)")
  }
}

NOTE:

If skip the encoding or using the encoding: .utf8 you will get the following errors -

The file “fileName.txt” couldn’t be opened because the text encoding of its contents can’t be determined.

OR

The file “fileName.txt” couldn’t be opened using text encoding Unicode (UTF-8).

so used encoding: .ascii while loading content of the text file.

if you want to simplify the syntax a bit the following is a function that would accomplish the goal as well:

private func loadTextWithFileName(_ filename: String) -> String? {
    guard let path = Bundle.main.path(forResource: filename, ofType: "txt"),
         let contents = try? String(contentsOfFile: path) else { return nil }
    return contents
}
Related