NSData dataWithContentsOfFile returning null

前端 未结 6 984
再見小時候
再見小時候 2021-02-19 11:19

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

-(void)readJsonFiles
{
    NSString *str=[[[NSBu         


        
相关标签:
6条回答
  • 2021-02-19 11:38

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

    NSString *str=[[NSBundle mainBundle] pathForResource:@"classes" ofType:@"json"];
    
    NSData *fileData = [NSData dataWithContentsOfFile:str];
    
    0 讨论(0)
  • 2021-02-19 11:43

    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
    }
    
    0 讨论(0)
  • 2021-02-19 11:44
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MyFile" ofType:@"txt"];  
    NSData *myData = [NSData dataWithContentsOfFile:filePath];  
    
    0 讨论(0)
  • 2021-02-19 11:50

    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!)
    
    0 讨论(0)
  • 2021-02-19 11:59

    You can follow this to get NSData from your document directory

    NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    stringPath  = [stringPath stringByAppendingPathComponent:@"JSON_FILE_NAME.json"];
    NSLog(@"stringpath %@",stringPath);
    NSData *fileData = [NSData dataWithContentsOfFile:stringPath];
    

    Hope this will work for you.

    0 讨论(0)
  • 2021-02-19 12:00

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

    That should not be nil.

    0 讨论(0)
提交回复
热议问题