Trying to load HTML content that contains images into either a UITextView or a WKWebView (I just need it rendered!)
However, when I load HTML into WKWebView, the images do not load and the view doesn't reload and respect the Autolayout constraints from before the content loads:
Relevant code is here:
webView.navigationDelegate = self
webView.loadHTMLString(body, baseURL: nil)
and
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if webView.isLoading == false {
webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { [weak self] (result, error) in
guard let safeSelf = self else {return}
if let height = result as? CGFloat {
print("height of webview: \(height)")
webView.frame.size.height += height
//Layout subviews?
}
})
}
}
However, with UITextView, according to the accepted answer found here I can do the following:
extension String {
var htmlToAttributedString: NSMutableAttributedString? {
guard let data = data(using: .unicode) else { return NSMutableAttributedString() }
do {
return try NSMutableAttributedString(data: data, options: [.documentType: NSMutableAttributedString.DocumentType.html], documentAttributes: nil)
} catch {
return NSMutableAttributedString()
}
}
and set it as such:
textView.attributedText = htmlString.htmlToAttributedString
This works well in terms of the Autolayout... for just texts, but it is not preserving images(doesn't even show an indication of where images would go), only text. Not event preserving fonts or font sizes used by the html.
I have directly used the accepted answer from that post and it does not preserve images, even though the OP asked for preserving images.
What is either a) the correct way to load content into a WKWebView and load the images (my Transport Security is set to allow arbitrary loads for this demo) or b) preserve images in UITextView's parsing of the HTML? I am given the html directly and not the URL.
EDIT: For testing purposes, I have hardcoded a small sample html in my code for use in UIWebView / WKWebView to mirror a portion of what I get from the API call.
let body = "<div class=\"media-attachment\"><a href=\"https://www.hnmagazine.com/2017/11/07/latinx-really-mean/\"><img src=\"https://testimages.weareher.com/feed/0/2018-08/t9Qc549F7uCtZdbdXx1ERLbXJN2EXIXVacouJDlX.png\"/></a><p class=\"media-caption\">via <a href=\"https://latinxontherise.podbean.com/\">Latinxontherise</a></p></div></div>"