Paul
Paul

Reputation: 101

Reading a text file from desktop at app startup

I need to display the contents of a text file located on the user's desktop in an NSTextView at startup . My code is not working -- is it off track?

NSError *err = nil;

NSString *filepath = @"~/Desktop/test.txt";

NSString *file = [NSString stringWithContentsOfFile:filepath 
                                           encoding:NSUTF8StringEncoding 
                                              error:&err];

if(!file) {

}

[textView setString:file];

Upvotes: 4

Views: 2586

Answers (2)

WrightsCS
WrightsCS

Reputation: 50727

Your path to the text file looks off ... possibly: /Users/USERNAME/Desktop/test.txt Also, try NSLog(@"Error: %@",[err description]); to see what errors are generated.

Upvotes: 0

Paul
Paul

Reputation: 130

@Shem. Sorry about that.

I fixed it like this:

 NSError *err = nil;

 NSString *filepath = @"~/Desktop/test.txt";
 filepath = [filepath stringByExpandingTildeInPath];

 NSString *file = [NSString stringWithContentsOfFile:filepath 
                                       encoding:NSUTF8StringEncoding 
                                          error:&err];

 if(!file) {

}

[textView setString:file];

Upvotes: 7

Related Questions