来自本地文件 URL 的 iPhone-NSData

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

谁能告诉我如何从本地文件的 URL中获取 NSData对象?

谢谢。

77910 次浏览
// Given some file path URL: NSURL *pathURL
// Note: [pathURL isFileURL] must return YES
NSString *path = [pathURL path];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];

Swift code:

let data = FileManager.default.contents(atPath: path)

To get this work you just need to do:

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];

Make sure your local URL starts with "file://" then you would just have to do this:

 NSData *fileData = [NSData dataWithContentsOfFile:fileURL.path];

For swift3 I found answer from following URL helpful

( I was getting following path , after capturing image using phonegap plugin

file:///var/mobile/Containers/Data/Application/B64B06DE-7976-45CF-9BE2-661F0F309A06/tmp/abcded.jpg )

https://stackoverflow.com/a/41043447/6383908

if let videoURL = URL(string: urlString), let videodata = try? Data(contentsOf: videoURL) { //Add code of Alamofire here }

guard let data = FileManager.default.contents(atPath: path) else
{ ...