iPhone - 来自本地文件URL的NSData

los*_*sit 82 iphone nsurl nsdata

我有一个NSURL对象,它给我一个本地文件的路径(在文档文件夹中).我想NSData用这个文件的内容填充一个对象.尝试使用,dataWithContentsOfURL:但这失败了.我知道该文件存在,因为iPhone SDK返回路径.

有人可以告诉我如何NSDataURL本地文件中获取对象吗?

谢谢.

Tim*_*Tim 160

// Given some file path URL: NSURL *pathURL
// Note: [pathURL isFileURL] must return YES
NSString *path = [pathURL path];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
Run Code Online (Sandbox Code Playgroud)

  • [NSFileManager docs](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html)在Threading Considerations下有这个说法:"方法可以安全地从多个线程调用共享的NSFileManager对象." 他们注意到的唯一例外是你打算从文件管理器的操作中处理委托回调; 我不认为这适用于此. (2认同)

小智 29

要完成这项工作,您只需要:

NSURL *imgPath = [[NSBundle mainBundle] URLForResource:@"search" withExtension:@"png"];
NSString*stringPath = [imgPath absoluteString]; //this is correct  

//you can again use it in NSURL eg if you have async loading images and your mechanism 
//uses only url like mine (but sometimes i need local files to load)
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:stringPath]];
UIImage *ready = [[[UIImage alloc] initWithData:data] autorelease];
Run Code Online (Sandbox Code Playgroud)