NSData dataWithContentsOfFile returning null

2019-04-04 06:59发布

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.

6条回答
家丑人穷心不美
2楼-- · 2019-04-04 07:08

You need to use pathforResource with resourcetype and check if there is data in your file.

That should not be nil.

查看更多
戒情不戒烟
3楼-- · 2019-04-04 07:17

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
}
查看更多
成全新的幸福
4楼-- · 2019-04-04 07:17
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MyFile" ofType:@"txt"];  
NSData *myData = [NSData dataWithContentsOfFile:filePath];  
查看更多
劳资没心,怎么记你
5楼-- · 2019-04-04 07:23

You can follow this to get NSData from your document directory

NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"YOUR_FOLDER_NAME"];

stringPath  = [stringPath stringByAppendingPathComponent:@"JSON_FILE_NAME.json"];
NSLog(@"stringpath %@",stringPath);
NSData *fileData = [NSData dataWithContentsOfFile:stringPath];

Hope this will work for you.

查看更多
SAY GOODBYE
6楼-- · 2019-04-04 07:32

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

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

NSData *fileData = [NSData dataWithContentsOfFile:str];
查看更多
Bombasti
7楼-- · 2019-04-04 07:34

There is the solution for Swift 3 :

//create a fil's path, decompose name and extension
let path = Bundle.main.path(forResource: "anim-gif-1", ofType: "gif")
//get the data asociated to this file
let file = NSData(contentsOfFile: path!)
查看更多
登录 后发表回答