Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSData dataWithContentsOfFile returning null

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.

like image 951
user3129278 Avatar asked Dec 27 '13 06:12

user3129278


3 Answers

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MyFile" ofType:@"txt"];  
NSData *myData = [NSData dataWithContentsOfFile:filePath];  
like image 191
TtheTank Avatar answered Sep 20 '22 14:09

TtheTank


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

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

NSData *fileData = [NSData dataWithContentsOfFile:str];
like image 30
TheAmateurProgrammer Avatar answered Oct 15 '22 15:10

TheAmateurProgrammer


It's failed to read your file for some reason. Use -dataWithContentsOfFile:options:error: to find out why.

NSError* error = nil;
NSData *fileData = [NSData dataWithContentsOfFile:str options: 0 error: &error];
if (fileData == nil)
{
   NSLog(@"Failed to read file, error %@", error);
}
else
{
    // parse the JSON etc
}
like image 6
JeremyP Avatar answered Oct 15 '22 13:10

JeremyP