【问题标题】:Can't Create a new file using NSData writeFile, NSFileManager and NSURL never returns the filePath [duplicate]无法使用 NSData writeFile、NSFileManager 和 NSURL 创建新文件永远不会返回文件路径 [重复]
【发布时间】:2013-08-18 04:42:30
【问题描述】:

我正在处理一个 iOS 应用程序,并且在这个问题上遇到了很大的麻烦,事情是这样的:

1.- 我正在创建一个基于一些 NSData 的文件 2.- 我正在尝试检索我刚刚创建的新文件的 NSURL

问题是 NSURL 似乎没有找到该文件,我尝试使用两种不同的方法创建该文件

NSdata * fileData = /*Gets the data of the file from the web*/

if([fileData writeToFile:databasePath atomically:YES])
{

    NSLog(@"path to resource :%@", [[[NSBundle mainBundle] pathForResource:@"myTMP"  ofType:@"epub"] description]);
    //This causes an exception cause the string is Nil but means that the file is created
    return [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"myTMP" ofType:@"epub"]];

}

如果我试试这个:

NSString* path=@"myTMP.epub";
[fileData writeToFile:path options:NSDataWritingAtomic error:&error];
NSLog(@"Write returned error: %@", [error localizedDescription]);

它永远不会创建新文件,任何帮助、建议、cmets 将不胜感激 最好的问候,

豪尔赫。

【问题讨论】:

  • fileData writeToFile 返回一个值,你能检查一下吗?根据值,您可以记录 error 值。
  • 这是stackoverflow.com/q/5853014/558933 的副本。还有多个关于此的问题 - 请搜索网站。
  • 我之前发现的所有问题都没有帮助,这就是我自己问的原因:S

标签: ios objective-c nsdata nsfilemanager


【解决方案1】:

出于明显的安全原因,您不得写入应用程序包。您需要写入 Documents 或其他应用程序包文件夹。使用此处记录的NSFileManagerURLsForDirectory:inDomains: 方法:

http://developer.apple.com/library/ios/DOCUMENTATION/FileManagement/Conceptual/FileSystemProgrammingGuide/AccessingFilesandDirectories/AccessingFilesandDirectories.html#//apple_ref/doc/uid/TP40010672-CH3-SW3

有关在 iOS 上读写文件的更多一般信息,请参阅http://developer.apple.com/library/ios/DOCUMENTATION/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW2

【讨论】:

    猜你喜欢
    • 2011-12-27
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    相关资源
    最近更新 更多