问题描述
我们在应用程序中使用webarchives有时因为将HTML +所有相关图像/ CSS /脚本等存储在桌面上的单个文件中,将其放入项目中,然后将其加载到UIWebView只需一次调用:
We are using webarchives in our apps sometimes as it is very convenient way to store HTML + all associated images/CSS/scripts/etc inside a single file on the desktop, put it into the project, and then load it into a UIWebView with a single call like that:
NSData *webArchiveData = /* ... Load data from a single file ... */ ;
[webView
loadData:webArchiveData
MIMEType:@"application/x-webarchive"
textEncodingName:@"utf-8"
baseURL:nil
];
然而,这停止了在iOS 6上运行:加载了HTML,但是通过相对URL引用的图像不是再次显示。
This stopped working on iOS 6 however: the HTML is loaded, but images referenced via relative URLs are not displayed anymore.
推荐答案
我从webarchive中的一些JavaScript中追踪到了location.href,发现在iOS 5及更低版本上是保存为webarchive的原始HTML的URL。它用作基本URL,因此可以正确解析从HTML(图像等)引用的资源的相对URL,然后在webarchive中找到它们(因为它们存储在原始绝对URL中)。
I traced location.href from a bit of JavaScript within the webarchive and found that on iOS 5 and lower this is the URL of the original HTML that was saved as webarchive. It was serving as a base URL, so relative URLs of resources referenced from the HTML (images, etc.) could be resolved properly and then found within the webarchive (as they are stored there with their original absolute URLs).
在iOS 6上,但跟踪location.href会给出类似 applewebdata:// 1B648BC1-F143-4245-A7AD-6424C3E3D227
的网址,所以所有相对URL都是相对于这个解析的,当然也不能在webarchive中找到。
On iOS 6 however tracing location.href gives URLs like applewebdata://1B648BC1-F143-4245-A7AD-6424C3E3D227
, so all relative URLs are resolved relative to this one and of course cannot be found in the webarchive anymore.
我发现的一个解决方法是将不同于nil的内容传递给loadData :MIMEType:textEncodingName:baseURL:,像这样:
One of the workarounds I found is to pass something different from nil into loadData:MIMEType:textEncodingName:baseURL:, like this:
[webView
loadData:serializedWebArchive
MIMEType:@"application/x-webarchive"
textEncodingName:@"utf-8"
baseURL:[NSURL URLWithString:@"file:///"] // Passing nil here won't work on iOS 6
];
它适用于iOS 6和iOS 5,并且转储location.href提供相同的绝对URL与以前一样的原始HTML。
It works on both iOS 6 and iOS 5 and dumping location.href gives the same absolute URL of the original HTML as before.
任何缺点/建议?
这篇关于iOS 6上的UIWebView不显示webarchives中具有相对URL的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!