NSData dataWithContentsOfFile返回null

我正在尝试使用此代码获取存在于我的xcode资源中的JSON文件

 -(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返回这个文件path的链接

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

但是当我loginfileData它返回我null 。 我不知道我在做什么错误。

而不是追加path,使用pathForResource:ofType:所以

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

由于某种原因无法读取您的文件。 使用-dataWithContentsOfFile:options:error:找出原因。

 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 } 
 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MyFile" ofType:@"txt"]; NSData *myData = [NSData dataWithContentsOfFile:filePath]; 

有Swift 3的解决scheme:

 //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!) 

您需要使用resourcefor的pathforResource并检查文件中是否有数据。

那不应该是零。

你可以按照这个从你的文档目录中获取NSData

 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]; 

希望这会为你工作。