I have an html string(which i got from an api response). Also i have some js file, css file, images and fonts on the app bundle.
I need to load these files along with the html string in WKWebView
the html string look like this
Thanks in advance
I have an html string(which i got from an api response). Also i have some js file, css file, images and fonts on the app bundle.
I need to load these files along with the html string in WKWebView
the html string look like this
Thanks in advance
Create a html below like this
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
<meta name="supported-color-schemes" content="light dark">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<div id="editor" contentEditable="true" placeholder="" class="placeholder"></div>
</div>
<script type="text/javascript" src="rich_editor.js"></script>
</body>
</html>
Load your html and css file in the html, I have used rich_editor.js and style.css
Load created html to webview like this
webView.loadFileURL(documentsUrl, allowingReadAccessTo: documentsUrl.deletingLastPathComponent())
Using below function insert your Html string that obtained from API
public func runJS(_ js: String, handler: ((String) -> Void)? = nil) {
webView.evaluateJavaScript(js) {(result, error) in
if let error = error {
print("WKWebViewJavascriptBridge Error: \(String(describing: error)) - JS: \(js)")
handler?("")
return
}
guard let handler = handler else { return }
if let resultBool = result as? Bool {
handler(resultBool ? "true" : "false")
return
}
if let resultInt = result as? Int {
handler("\(resultInt)")
return
}
if let resultStr = result as? String {
handler(resultStr)
return
}
handler("") // no result
}
}
To call this function
runJS("RE.insertHTML('yourHtmlString')")