IOS Programming - Read a Text File in IOS



In this tutorial we will be looking at how to load a text file into your iOS Application. We’re going to be creating a text file in the Mac Application ’TextEdit’ and then loading the contents of the file into an NSString. Then we’re going to put the contents of the NSString into a UITextView and display it in the App. Lets get started!

Step 1: Creating the Text File
First of all, we need to create the text file that we’re going to load in our App. Load up a text editor (I’ve used TextEdit) and type in some text that you want to be read by the App. Then save it as a Plain Text file (.txt) and remember the file name.

1

Step 2: Create our Xcode Project
Open up Xcode and create a Single View Application. Name the project anything you want.

2

Step 3: Import the Text File
Next we need to import the text file into our Xcode project. Drag it into the project and select ‘Copy items into destination group’s folder’.

3

Step 4: Write our .h
In our .h file, we need to declare an IBOutlet for our UITextView so we can hook it up in interface builder.

4

Step 5: Hook things up in IB


Next, head into Interface Builder. Drag a UITextView from the library into a view. Go into the Inspector and drag from our declared outlet onto the UITextView we just created.

5

Step 5: Write the .m file

We want the text to load when the App loads, therefore we are going to put our code into the viewDidLoad. First off, we will create an NSString and then give it the location of the file we want to load. I named my file ‘TextFile.txt’. Make sure you enter the exact name that you called yours. Next we are going to create an if statement that fires if ‘filePath’ is true. i.e if it has found the location of the file. In the if statement we are going to load the contents of the text file into an NSString and then give our textView the contents of that string.

We’re done!

6

Step 5: Build and Run!


Now we can build and run to make sure it works! As you can see, the text that was in the text file has loaded into our UITextView in our App!

7

Download the Sample Project


Xcode

Download the Xcode Project here: TextFile

I hope you find this tutorial useful. If you have any questions or improvements, please email me using the Contact Page or Tweet me @JASApplications

Nhận xét

Bài đăng phổ biến