Loading the Contents of a Text File

Most of the time if you want text to appear on your user interface, you just type it directly into your user interface, such as editing a text field or label. You can also create and edit text using the Attributes Inspector pane as well, but if you need to display large amounts of text, it’s often easier to create and edit that text in a separate file.

Once you create a separate text file (not stored in a word processor format like the Microsoft Word .docx file format), you can then drag and drop that text file into the Project navigator pane.

When you drag and drop a file in the Project navigator pane, a window will appear to display options for adding a file. Make sure the “Copy items if needed” check box is selected.

To retrieve a file, you must specify the filename and extension. If you stored text in a file called “Xcode.txt,” then the filename would be “Xcode” and the extension would be “txt”.

If the text file exists, then you can store the contents of that file in a variable name. If the file can’t load or the file you specify isn’t found, then you need to handle this possible error so your program doesn’t crash. You can do all this with the following code:

        if let filepath = Bundle.main.path(forResource: "Xcode", ofType: "txt") {
            do {
                let contents = try String(contentsOfFile: filepath)
            } catch {
                // Contents could not be loaded
        } else {
            // Xcode.txt file not found!

The above code would store the contents of the “Xcode.txt” file in the “contents” variable. Just remember that if your file were called “Data.asc” then the above code would replace “Xcode” with “Data” and “txt” with “asc”.

To see how this works in a simple macOS program, download and run the following sample program that displays a text view in a window and a push button. By clicking on the push button, you can load the contents of the Xcode.txt file:


April 29th, 2017 by
HTML Snippets Powered By : XYZScripts.com