Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 766
ercan Avatar asked Jun 19 '26 11:06

ercan


1 Answers

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");
}
like image 173
Sadiq Jaffer Avatar answered Jun 21 '26 01:06

Sadiq Jaffer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!