milo
milo

Reputation: 555

Getting the contents of a file in Xcode

In my project I have a plain text file called GAME.js, and I'm trying to get the contents of the file.

[NSString stringWithContentsOfFile:@"GAME.js" encoding:NSUTF8StringEncoding error:nil];

sounds like it should work, but it's just returning an empty string.

Please help me fix this.

Upvotes: 1

Views: 2967

Answers (2)

chown
chown

Reputation: 52728

If you pass in a NSError it will tell you exactly what the problem is:

NSError *error = nil;
NSString *myString = [NSString stringWithContentsOfFile:@"GAME.js" encoding:NSUTF8StringEncoding error:&error];

if (error) {
    NSLog(@"%@", [error localizedDescription]);
} else {
    NSLog(@"%@", myString);
}

NSError Documentation


Also, check to see if it is in your documents directory which can be accessed with NSSearchPathForDirectoriesInDomains:

NSError *error = nil;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fullPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"GAME.js"];

NSString *myString = [NSString stringWithContentsOfFile:fullPath encoding:NSUTF8StringEncoding error:&error];

if (error) {
    NSLog(@"%@ - %@", [error localizedDescription], [error localizedFailureReason]);
} else {
    NSLog(@"%@", myString);
}

Upvotes: 2

Chris Ledet
Chris Ledet

Reputation: 11628

Put GAME.js into the Resources folder in your Xcode project and use the following code to get the contents of the file.

NSError *error = nil;
NSString* path = [[NSBundle mainBundle] pathForResource:@"GAME" ofType:@"js"];
NSString* gameFileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];

Upvotes: 8

Related Questions