Ios NSData datawithcontentsoffile返回null

Ios NSData datawithcontentsoffile返回null,ios,objective-c,nsdata,Ios,Objective C,Nsdata,我有以下代码可以从iphone的documents目录获取文件: NSString *docsDir; NSString *realpath; NSArray *dirPaths; dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); docsDir = dirPaths[0]; realpath=[[NSString alloc] initWithString:

我有以下代码可以从iphone的documents目录获取文件:

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找到该文件,但nsdata返回null,但两者的路径相同

我的文件大小约为60kb


你知道为什么会这样吗?我遗漏了什么吗?

代码你在这里写的看起来不错, 我建议您选择另外一种方法,它也需要NSError实例

               `dataWithContentsOfFile:options:error:`
如果出现问题,您将尝试将该文件内容转换为NSData,那么您仍然会得到一些错误描述,该错误描述可能会对您有所帮助

我希望它能对你有所帮助。。。。。。欢呼

realpath=[[NSString alloc] initWithString:
      [docsDir stringByAppendingPathComponent: @"2_program.db"]];
这里你错过了一个/ 将上述语句更改为

realpath = [[NSString alloc] initWithString:
      [docsDir stringByAppendingPathComponent: @"/2_program.db"]];
请尝试Matt Gallagher的优秀NSData+Base64类别,并附上以下代码

    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");
}

使用
dataWithContentsOfFile:options:error:
获取有关失败原因的信息。文件路径是什么?它是否有
文件://
方案?您的
uploadedData
是否返回结果,还是仅您的
uploadedDataBase64
返回零?问题在于“base64forData”方法中我检查了以下选项:错误和错误为空。同时检查uploadeddata,它返回“仅限
-stringByAppendingPathComponent:
自动放入路径分隔符。检查文档中的“返回值通过向接收器追加aString生成的新字符串,必要时在前面加一个路径分隔符”。因此它将添加分隔符。@JeremyP您还没有看到您提供的链接中的示例表。每个示例中都有/吗表格的第一行是
[@”/tmp“stringByAppendingPathComponent:@“scratch.tiff”]
的示例,您得到的答案是
@”/tmp/scratch.tiff“
。请注意,该方法本身是如何添加路径分隔符的。