简体   繁体   English

将本地图片加载到 WKWebView

[英]Loading local images into WKWebView

I'm trying to get WKWebView to display locally downloaded images in a WKWebView .我试图让WKWebView到显示本地下载的图像WKWebView The webview normally displays HTML, which is retrieved remotely. webview 通常显示 HTML,这是远程检索。 The contents of the HTML can sometimes contain remote links to images. HTML 的内容有时可以包含图像的远程链接。 My app parses the HTML and looks for these HTML tags, downloads the file it is referencing and subsequently replaces the remote link with a local one.我的应用程序解析 HTML 并查找这些 HTML 标签,下载它引用的文件,然后用本地链接替换远程链接。

Normally speaking, this wouldn't be very difficult but the images aren't being displayed, presumably due to the images and the local HTML files for the webview being in two separate directories (the documents directory and the app bundle directory respectively).通常来说,这不会很困难,但是图像没有被显示,大概是因为图像和 webview 的本地 HTML 文件位于两个单独的目录(分别是文档目录和应用程序包目录)。 I've seen people suggest moving the download destination of the images to the same directory as where the HTML files are but this isn't an option for me as I don't want to start mixing up files downloaded by the user with local assets.我见过有人建议将图像的下载目的地移动到与 HTML 文件所在的目录相同的目录,但这对我来说不是一个选项,因为我不想开始将用户下载的文件与本地资产混合在一起.

What would be my best course of action here?我在这里最好的行动方针是什么?

Well, I've found a workaround.嗯,我找到了一个解决方法。 Instead of locally storing the images and referencing them in the HTML files, I'm now instead converting the images to Base64 and then adding them to the HTML.我现在不是在本地存储图像并在 HTML 文件中引用它们,而是将图像转换为 Base64,然后将它们添加到 HTML。 It's not ideal but it gets the job done.这并不理想,但它完成了工作。 I'm going to leave this question open in case someone ever manages to find an actual solution.如果有人设法找到实际解决方案,我将保留这个问题。

To display cached HTML referencing cached resources in a WKWebView :要在WKWebView显示引用缓存资源的缓存 HTML:

  1. For each of the resources within your HTML content string, cache it into the directory as provided by NSTemporaryDirectory() .对于 HTML 内容字符串中的每个资源,将其缓存到NSTemporaryDirectory()提供的目录中。 So an image tag like:所以像这样的图像标签:

    ...<img src='https://www.myimage.com/example_image.png'/>...

    should be cached and replaced into something like this:应该被缓存并替换成这样的:

    ...<img src='/private/var/mobile/Containers/Data/Application/527CF4FC-9319-4DFF-AB55-9E276890F5DC/tmp/example_image.png'/>...

  2. Now cache the HTML content string with the replaced resource URLs.现在使用替换的资源 URL 缓存 HTML 内容字符串。 It must also be cached in the directory provided by NSTemporaryDirectory() .它也必须缓存在NSTemporaryDirectory()提供的目录中。 One difference here is that it must be cached (and later referenced) using the file:// protocol as a restriction of caching the string using NSData (see sample code).这里的一个区别是它必须使用file://协议缓存(并在以后引用)作为使用NSData缓存字符串的限制(参见示例代码)。

    For example file:///private/var/mobile/Containers/Data/Application/527CF4FC-9319-4DFF-AB55-9E276890F5DC/tmp/my_html_content_string.html例如file:///private/var/mobile/Containers/Data/Application/527CF4FC-9319-4DFF-AB55-9E276890F5DC/tmp/my_html_content_string.html

A few things to point out:有几点需要指出:

  • You cannot load the HTML as a raw string ( loadHTMLString:baseURL: ).您不能将 HTML 加载为原始字符串 ( loadHTMLString:baseURL: )。
  • You cannot reference the cached resource within your HTML string using the file:// protocol.您不能使用file://协议在 HTML 字符串中引用缓存资源。 That may work in a UIWebView , but will not work in the WKWebView .这可能适用于UIWebView ,但不适用于WKWebView

Objective-C目标-C

// To cache the HTML string:
NSString *HTML = <HTML CONTENT WITH CACHED RESOURCES>;
NSData *data = [HTML dataUsingEncoding: NSUTF8StringEncoding];
[data writeToURL: cachedHTMLURL atomically: YES];

// To load the store HTML file:
[myWKWebView loadRequest: [NSURLRequest requestWithURL: cachedHTMLURL]]; // (file://.../tmp/my_html_content_string.html)

Swift斯威夫特

// To cache the HTML string:
let HTML = <HTML CONTENT WITH CACHED RESOURCES>
let data = HTML.data(using: String.Encoding.utf8)
do {
    try data.write(to: cachedHTMLURL, options: .atomic)
} catch {
    print(error)
}

// To load the store HTML file:
myWKWebView.load(URLRequest(url: cachedHTMLURL)) // (file://.../tmp/my_html_content_string.html)

I had the same problem with WKWebView as it can not load both html strings and images at the same time for security purposes.我对 WKWebView 有同样的问题,因为出于安全目的,它无法同时加载 html 字符串和图像。 I switched to UIWebView, which is deprecated, but I was able to load both html strings and referenced images at the same time.我切换到不推荐使用的 UIWebView,但我能够同时加载 html 字符串和引用的图像。

I developed a definitive solution for the company I work for.我为我工作的公司开发了一个明确的解决方案。 But it relies on the html / javascript side.但它依赖于 html/javascript 方面。 Anywhere inside your html code where you will reference to a local image <img src="..."/> you should set this "src" dynamically, and it will work seamlessly.在您的 html 代码中您将引用本地图像<img src="..."/>您应该动态设置此"src" ,它会无缝地工作。

function getLocalURL(path) {
    let origin = window.location.origin
    if (origin == "file://") {
        return origin + window.location.pathname.replace("/index.html","") + path
    }
    return path
}

You should, clearly, rename index.html to whatever is your main .htm(l) filename :)显然,您应该将 index.html 重命名为您的主要 .htm(l) 文件名:)

Usage :用法

getLocalURL("/local_images/location_icon.png")

Will return a WKWebView working path for the referenced local image path:将返回引用的本地图像路径的 WKWebView 工作路径:

"file:///Users/arthurdapaz/Library/Developer/CoreSimulator/Devices/5073AF19-26A0-460E-BC82-E89100B8E1AB/data/Containers/Data/Application/2B099343-0BF5-4849-B1C2-2512377A9772/Documents/distDriver/local_images/location_icon.png"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM