Search code examples
iosobjective-cnsdatansfilemanager

Get NSData from a file


I am trying get NSData of an own file.

My code is as follow, but NSData returned is always nil… (As you can see, I check if the file exists previously)

if ([[NSFileManager defaultManager] fileExistsAtPath:path]){
    NSData * data = [[NSFileManager defaultManager] contentsAtPath:path];  
}

Any idea? Thanks!


Solution

  • It's possible that path is a folder, in which case fileExistsAtPath will return YES, but no data can be read. You can add some extra debugging by reading the data as follows:

    NSError* error = nil;
    NSData* data = [NSData dataWithContentsOfFile:path  options:0 error:&error];
    NSLog(@"Data read from %@ with error: %@", path, error);
    

    The log output will display the actual error that occurred.