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

有人可以告诉我怎样才能从本地文件的NSData得到URL对象?

感谢。

有帮助吗?

解决方案

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

其他提示

要得到这个工作,你只需要做的:

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

确保您的本地网址开头 “文件://” 那么你就只需要做到这一点:

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

有关swift3我发现答案从下面的URL有帮助

(我得到以下路径,使用的PhoneGap插件捕获图像之后

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

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

如果让videoURL = URL(字符串:urlString),让可视数据=尝试?数据(contentsOf:videoURL){      //添加Alamofire的代码在这里 }

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top