crazy2431
crazy2431

Reputation: 801

How to read a text file from my application's bundle and display it in a UITextView

I want to read a text file called "config.txt" from my application's bundle and display it in a UITextView. The code below is not working, can anyone help me?

IF i want to display it on a View then what i should do as well.

I have a IBOutlet to a UITextView, also please tell me how to change the text font and colour programmatically.

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"config" ofType:@"txt"];  
if (filePath) {  
    NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding];
    if (myText) {  
        textView.text= myText;    
    }
}


[super viewDidLoad];

Upvotes: 2

Views: 3154

Answers (4)

Jayprakash Dubey
Jayprakash Dubey

Reputation: 36447

The below code worked for me :

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"config" ofType:@"txt"]; 

if (filePath) {  
    NSError *error;
    NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];

    if(!error) {
        if (myText) {  //config file contains text
            textView.font = [UIFont fontWithName:@“Times New Roman” size:16.0f];
            textView.textColor = [UIColor blackColor];
            textView.text= myText;    
        }
    }
    else {
        //Handle error while reading file
    }
}
else {
    //File path does not exists. Handle error
}

Upvotes: 0

Cassie Li
Cassie Li

Reputation: 11

see whether your config.txt is normal or messy code I mean you may check your txt file in the X-code surroundings

Upvotes: 0

Andrew
Andrew

Reputation: 7710

Check to make sure textView is not nil and that you setup the IBOutlet connection in Interface Builder.

To set the font and color of the UITextView programmatically, use:

textView.font = [UIFont fontWithName:@"Helvetica" size:18.0f];

and

textView.textColor = [UIColor blueColor];

See:

Upvotes: 1

Keller
Keller

Reputation: 17081

Is your file extension ".text" or ".txt"?

Also, why are you reading the file into an NSData object and then an NSString?

Upvotes: 0

Related Questions