Apple's recommendation:
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 new WKWebView
. 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 of loadHTMLString(...)
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
's
loadHTMLString(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?!)
See Question&Answers more detail:
os