如何从ios webview的文档目录读取图像文件

我正在下载图像文件并写入文件目录如下所示:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *objURL = @"http://test.test.com/file/image.png"; NSURL *objurl = [NSURL URLWithString:objURL]; NSData *imgData = [NSData dataWithContentsOfURL:objurl]; NSString *imgFile = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"image.png"]; [imgData writeToFile:imgFile atomically:YES]; 

在我的webView中,我从我的包资源中加载了一个html文件,用在我的webView中,但是如何在html中使用标签来读取文档目录中的image.png?

 <html> <body> <img src="../what/is/the/path/to/use/image.png" /> </body> </html> 

您可以使用带有file:// scheme的绝对path来提供此图像的URL:

 NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)[0]; NSString *filePath = [NSString stringWithFormat:@"file://%@/image.png", documentsDirectory]; 

然后,您可以运行一些JavaScript来更新src标记以将其更新为新path:

 NSString *javascript = [NSString stringWithFormat:@"var imageElement = document.getElementById('localFile'); imageElement.setAttribute('src', '%@');", filePath]; [self.webView stringByEvaluatingJavaScriptFromString:javascript]; 

在你的HTMLpath看起来像这样:

 <html> <body> <img id="localFile" src="file:///var/mobile/Applications/3D7D43E8-FA5E-4B19-B74C-669F7D1F3093/Documents/image.png" /> </body> </html> 

而不是评估JavaScript,我只是在我的html内容中写下一个占位符,并直接将其replace为所需的内容:

 NSString *htmlFilePath = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html"]; NSString *htmlString = [NSString stringWithContentsOfFile:htmlFilePath encoding:NSUTF8StringEncoding error:&error]; if (error) { // handle error return; } NSString *imageFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"sample_image.png"]; NSURL *imageFileURL = [NSURL fileURLWithPath:imageFilePath]; NSString *sampleImageReplacement = [NSString stringWithFormat:@"<img src=\"%@\" />", [imageFileURL absoluteString]]; // Replace the placeholder w/ real content, // and of course, we can also replace it w/ empty string // if the image cannot be found. htmlString = [htmlString stringByReplacingOccurrencesOfString:@"%sample_image%" withString:sampleImageReplacement]; ... [webView loadHTMLString:htmlString baseURL:nil]; 

您可以从应用程序包中加载图像,但无法直接从文档目录加载图像。

但有一个工作。

使用CocoaHTTPServer创build一个InAppHttpServer,你可以在web视图中使用http URL来访问documents目录中的图像。

要不然

将图像转换为base64,并使用webview的evaluatejavascript加载图像

 document.getElementById('img').setAttribute( 'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' ); 

你不能从头开始绑定图像源。 你将不得不通过JavaScript来做到这一点。

您需要通过评估JS将图像的path传递给UIWebView。 在这里,你可以传递你的图像的path和JS将加载到各自的HTML标签的图像。