song wei
song wei

Reputation: 7

display the txt file in a UITextView

I am new to iPhone development,need help.I am developing an iPhone application which contains a UITextView.I have a list of txt files in the documents .I am trying to use a UITextView to display the contents of the text file, but I have trouble getting it to display anything at all. I use these codes want the UITextView to display the txt file :

  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
self.frlistName2 = [[manager contentsOfDirectoryAtPath:documentsDirectoryPath error:nil]pathsMatchingExtensions:[NSArray arrayWithObject:@"txt"]];
NSString *obj = @".txt";
frlisturls2 = [[NSMutableArray alloc] initWithObjects:nil];
NSString *temp;
NSMutableString *mp3Path = [[NSMutableArray alloc] init];
int j =0;
for(int i =0 ; i< [frlistName2 count]; i++)
{
    mp3Path  = [NSMutableString stringWithString:documentsDirectoryPath];
    [mp3Path appendString:@"/"];

    temp = [frlistName2 objectAtIndex:i];
    if([temp hasSuffix :obj])
    {
        [mp3Path appendString: temp];
        [frlisturls2 addObject: mp3Path];
        j++;
    }
    [mp3Path release];
}
NSLog(@"frlisturls2 is%@:",frlisturls2);
[super viewDidLoad];
fileName = [[NSString alloc]init];
fileName=[frlisturls2 objectAtIndex:iRow ];
NSLog(@"the fileName is %@",fileName);
stringSources = [NSString stringWithContentsOfFile: fileName encoding:NSUTF8StringEncoding error:nil];
frtextview=[[UITextView alloc]init];
[frtextview setText:stringSources];
NSLog(@"the file is :%@",stringSources);

the filename display the right url,but the stringSource do not have words.Sorry for the long post!I hope for you help!

Upvotes: 0

Views: 3531

Answers (1)

Webber Lai
Webber Lai

Reputation: 2022

This is how I read the txt file to txtView

But sometimes the file can't open by text editor ,

NSString *filePath = @"Users/macbookpro/Library/Application
 Support/iPhone Simulator/4.3.2/Applications/ ...
 /Documents/sample.txt"; 
NSString *txtContent = [[NSString alloc]
                                    initWithContentsOfFile:filePath
                                    encoding:NSUTF8StringEncoding
                                    error:&error];

load txtContent to your textView.text

Upvotes: 1

Related Questions