如何从ios webview读取文档目录中的图像文件 [英] How to read image file at documents directory from ios webview

查看:29
本文介绍了如何从ios webview读取文档目录中的图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am downloading image file and write to documents directory like below:

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 中,我从我的 bundle 资源中加载了一个 html 文件以在我的 webView 中使用,但是我如何在 html 中使用标签来读取文档目录中的 image.png?

In my webView, I loaded a html file from my bundle resource to use in my webView, but how do I have the tag in html to read the image.png in documents directory?

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

推荐答案

您可以使用带有 file:// 方案的绝对路径来提供此图像的 URL:

You could give the URL for this image using an absolute path with a file:// scheme:

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

然后您可以运行一些 javascript 来更新 src 标记以将其更新为新路径:

You could then run some javascript to update the src tag to update it to the new path:

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

在您的 HTML 中,路径类似于:

In your HTML the path would look like something like:

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

这篇关于如何从ios webview读取文档目录中的图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆