WKWebView无法使用loadHTMLString(_,baseURL :)加载图像和CSS [英] WKWebView fails to load images and CSS using loadHTMLString(_, baseURL:)
问题描述
示例
我定义了一个简单的 htmlString
在我的视图控制器类中:
让imageName =image.png
let libraryURL:URL //默认库URL
var htmlString:String {
return< html> ...< img src = \\(imageName)\/> ...< / html>
//...表示更有效的HTML代码,包括标题和正文标记
}
图像存储在根库文件夹中,因此其URL为:
让imageURL = libraryURL.appendingPathComponent(imageName)
现在我加载 htmlString
进入网络视图:
webView.loadHTMLString(htmlString,baseURL:libraryURL)
即使 baseURL $ c $也无法加载图片c>设置正确。
解决方案的想法
-
也许
WKWebView
解决相对路径时遇到问题所以我的第一个想法是在HTML字符串中使用绝对路径。
→❌不起作用。 -
所以,回顾 - 方法是有效的,功能是有效的,只是你做错了。为了帮助您解决您的解决方案的问题,我将添加一些建议:
1.请记住,模拟器文件系统不区分大小写,设备文件系统区分大小写即可。因此,如果你的文件名是html中的小写 - 这在设备上不起作用。8fFsD.png!= 8ffsd.png
2.请记住,在复制资源时,XCode会忽略您的文件夹结构。因此,如果你的html有< img src =。/ img / 1.png>
,你的XCOde项目的文件夹结构就像test.htm
img /
1.png
2.png
构建后它将被展平,因此test.htm和1.png和2.png将位于同一级别
test.htm
1.png
2.png
我几乎可以肯定,在你验证这两个假设后,你会得到这个方法。
In apps that run in iOS 8 and later, use the WKWebView class instead of using UIWebView.
Thus, I have replaced my good old
UIWebView
with a shiny newWKWebView
. But what I thought to be an easy exercise (simply swapping the classes and replacing the delegate methods) turned out to be a real mess.The Problem
When I load an HTML string using
loadHTMLString(String, baseURL: URL?)
the web view loads and renders the pure HTML but it doesn't load any images or CSS files referenced inside the
htmlString
.This happens only on a real device!
In Simultor all referenced resources are loaded correctly.Example
I have defined a simple
htmlString
in my view controller class:let imageName = "image.png" let libraryURL: URL // The default Library URL var htmlString: String { return "<html> ... <img src=\"\(imageName)\" /> ... </html>" // "..." represents more valid HTML code incl. header and body tags }
The image is stored in the root Library folder so its URL is:
let imageURL = libraryURL.appendingPathComponent(imageName)
Now I load the
htmlString
into the web view:webView.loadHTMLString(htmlString, baseURL: libraryURL)
and it doesn't load the image even though the
baseURL
is set correctly.Ideas for a Solution
Maybe
WKWebView
has a problem with resolving relative paths so my first idea was to use absolute paths inside the HTML string instead.
→ ❌ Doesn't work.Two answers to another SO post suggested that using
loadFileURL(URL, allowingReadAccessTo: URL)
instead ofloadHTMLString(...)
works in iOS 9+.
→ ✅ That works.
However, I cannot use solution 2 because my HTML files are encrypted and the decrypted files must not be stored on the disk.
Question
Is there any way to load local resources like images and styles using the
WKWebView
'sloadHTMLString(String, baseURL: URL?)
function? Or is still a bug in iOS 9+?
(I just cannot believe that Apple provides and recommends using a web view that cannot load any local web content from inside an HTML string?!)
解决方案Without taking a look at your actual project it's difficult to give some hundreed percent sure advices.
However:
class ViewController: UIViewController { var webView = WKWebView() override func viewDidLoad() { super.viewDidLoad() webView.translatesAutoresizingMaskIntoConstraints = false let views = [ "webView" : webView ] view.addSubview(webView) var constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[webView]|", options: [.AlignAllLeading, .AlignAllTrailing], metrics: nil, views: views) constraints.appendContentsOf(NSLayoutConstraint.constraintsWithVisualFormat("V:|[webView]|", options: [.AlignAllTop, .AlignAllBottom], metrics: nil, views: views)) NSLayoutConstraint.activateConstraints(constraints) let path = NSBundle.mainBundle().pathForResource("ios - WKWebView fails to load images and CSS using loadHTMLString(_, baseURL_) - Stack Overflow", ofType: "htm") let url = NSURL(fileURLWithPath: path!) webView.loadHTMLString(try! String(contentsOfURL: url), baseURL: url.URLByDeletingLastPathComponent) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
I think the key point here is
baseUrl
parameter, you should setup it correctly. In my case i've used html's url without last path component - e.g. containing folder. This works fine on both device & simulator - check device snapshot. I've uploaded sample project to https://github.com/soxjke/WKWebViewTest so you can take a look (i've removed codesigning info from git)So, to recap - method is working, functionality is working, just you do something wrong with it. To help you get what's wrong with your solutions, i'll add some suggestions: 1. Remember, that simulator filesystem is case-insensitive, device filesystem is case-sensitive. So if you have your filenames in html in lowercase - this won't work on device.
8fFsD.png != 8ffsd.png
2. Remember, that when copying resources, XCode ignores your folder structure. So if your html has<img src="./img/1.png">
and your XCOde project has folder structure liketest.htm img/ 1.png 2.png
After build it will be flattened, so test.htm and 1.png and 2.png will reside on same level
test.htm 1.png 2.png
I'm almost sure, after you verify these two assumptions, you'll get this method working.
这篇关于WKWebView无法使用loadHTMLString(_,baseURL :)加载图像和CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!