Search code examples
iosobjective-cnsdata

NSData datawithcontentsoffile returns null


i have below code for getting a file from iphone's documents directory:

NSString *docsDir;
NSString *realpath;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];

realpath=[[NSString alloc] initWithString:
          [docsDir stringByAppendingPathComponent: @"2_program.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: realpath ] == YES)
{
    NSLog(@"find file");
    NSData *uploadedData=[NSData dataWithContentsOfFile:realpath];
    NSString * uploadedDataBase64= [NSString base64forData:uploadedData];
    NSLog(@"base64: %@",uploadedDataBase64);
}
else
{
    NSLog(@"not found");
}

filemanager finds the file but nsdata returns null however both of them got the same path

my file's size about 60kb

any ideas why could it be happen? am i missing somthing?


Solution

  • Try this great NSData+Base64 category by Matt Gallagher along with the code below

        NSString *realpath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent: @"2_program.db"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:realpath]){
        NSLog(@"find file");
        NSData *uploadedData=[NSData dataWithContentsOfFile:realpath];
        NSString *uploadedDataBase64=[[[NSString alloc]initWithData:uploadedData encoding:NSUTF8StringEncoding] base64EncodedString];
        NSLog(@"base64: %@",uploadedDataBase64);
    }
    else{
        NSLog(@"not found");
    }