ios - NSData datawithcontentsofffile 返回 null

标签 ios objective-c nsdata

我有以下代码用于从 iphone 的文档目录中获取文件:

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

任何想法为什么会发生?我错过了什么吗?

最佳答案

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

关于ios - NSData datawithcontentsofffile 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23993289/

相关文章:

android - 如何使用分离的 expo 从 native 应用程序生成独立签名的 APK?

ios - rx_itemsWithCellFactory 调用语法

iphone - NSData 字节浮点 - iPhone SDK

ios - 在 RxSwift 中从 ViewModel 获取字符串到 View

iphone - 如何将caf High quality(sample rate)改成caf Low quality(sample rate)

objective-c - 如何在 Facebook iOS SDK 上存储多个分值

ios - 快速调用 Objective-c 函数

ios - 如何将 dispatch_data_t 转换为 NSData?

ios - 写入文件时丢失字节

ios - 如何像在 CNN 应用程序中那样在 UITableView 上扩展图像