Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Text File in Document Folder - Iphone SDK

I have this code below:

    NSString *fileName = [[NSUserDefaults standardUserDefaults] objectForKey:@"recentDownload"];
    NSString *fullPath = [NSBundle pathForResource:fileName ofType:@"txt" inDirectory:[NSHomeDirectory() stringByAppendingString:@"/Documents/"]];
    NSError *error = nil;

    [textViewerDownload setText:[NSString stringWithContentsOfFile:fullPath encoding: NSUTF8StringEncoding error:&error]];
  • textviewerdownload is the textview displaying the text from the file. The actual file name is stored in an NSUserDefault called recentDownload.

  • When I build this, I click the button which this is under, and my application crashes.

  • Is there anything wrong with the syntax or just simple error?

like image 792
lab12 Avatar asked Apr 25 '10 19:04

lab12


2 Answers

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:@"myfile.txt"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:myPathDocs])
    {
        NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"txt"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager copyItemAtPath:myPathInfo toPath:myPathDocs error:NULL];
    }       

    //Load from File
NSString *myString = [[NSString alloc] initWithContentsOfFile:myPathDocs encoding:NSUTF8StringEncoding error:NULL];

This worked for me

Anyway, thank you all..

like image 45
iOS Avatar answered Sep 24 '22 23:09

iOS


The NSBundle class is used for finding things within your applications bundle, but the Documents directory is outside the bundle, so the way you're generating the path won't work. Try this instead:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                     NSUserDomainMask,
                                                     YES);

NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:@"recentDownload.txt"]; 
like image 71
jlehr Avatar answered Sep 24 '22 23:09

jlehr