Wkwebview Fails to Load Images and CSS Using Loadhtmlstring(_, Baseurl:)

iOS WKWebview loadHTMLString(_ baseURL:) fails to load images and read css

I wish I had a better answer and if anybody has a better answer I will gladly accept it.
I ended up moving my files to the temp directory :( I've used this -

extension FileManager
{
func copyToTemporaryDirectory(itemIn itemURL: URL) -> URL?
{
let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
let fileName = itemURL.lastPathComponent
let copyURL = tempDirectoryURL.appendingPathComponent(fileName)
let fileManager = FileManager.default

do {

if fileManager.fileExists(atPath: copyURL.path)
{
try fileManager.removeItem(at: copyURL)
}

try FileManager.default.copyItem(at: itemURL, to: copyURL)

return copyURL

}
catch let error
{
logger.debug("copyItem error: \(error.localizedDescription)")
return nil
}
}
}

and then loadHtmlString with the URL to this directory. from this directory, WKWebview is allowed to get everything.

WkWebView won't loadHTMLstring

SWIFT

You might be making it a bit too complicated. This worked for me ...

First, import WebKit

Second, create an @IBOutlet under your class:

@IBOutlet weak var webView: WKWebView!

Third, place the following in your viewDidLoad():

let htmlString:String! = "\(YourString)"
webView.loadHTMLString(htmlString, baseURL: NSBundle.mainBundle().bundleURL)

SWIFT 3 update

webView.loadHTMLString(htmlString, baseURL: Bundle.main.bundleURL)

WKWebView cannot load local resource in HTML

Add all the HTML directories & files in your project.

let webView = WKWebView()
if let htmlPath = Bundle.main.path(forResource: "directory/index", ofType: "html") {
let htmlUrl = URL(fileURLWithPath: htmlPath, isDirectory: false)
webView.loadFileURL(htmlUrl, allowingReadAccessTo: htmlUrl)
view = webView
}

Sample Image



Related Topics



Leave a reply



Submit