NSData dataWithContentsOfFile returning null

user3129278 picture user3129278 · Dec 27, 2013 · Viewed 27.5k times · Source

I am trying to fetching a JSON file which exist in my xcode resources using this code

-(void)readJsonFiles
{
    NSString *str=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"classes.json"];
    NSLog(@"Path: %@", str);
    NSData *fileData = [NSData dataWithContentsOfFile:str];
    NSLog(@"Data: %@", fileData);
    SBJsonParser *parser = [[SBJsonParser alloc] init] ;
    NSDictionary *jsonObject = [parser objectWithData:fileData];
    NSLog(@"%@", jsonObject);
}

path return me this link of file path

/Users/astutesol/Library/Application Support/iPhone Simulator/6.0/Applications/A4E1145C-500C-4570-AF31-9E614FDEADE4/The Gym Factory.app/classes.json

but when I log fileData it return me null . I don't know where I am doing mistake.

Answer

TheAmateurProgrammer picture TheAmateurProgrammer · Dec 27, 2013

Instead of appending the path, use pathForResource:ofType:, so

NSString *str=[[NSBundle mainBundle] pathForResource:@"classes" ofType:@"json"];

NSData *fileData = [NSData dataWithContentsOfFile:str];