I have searched and found many posts where I am getting solution to load a CSS file from bundle or from a String. But I have my CSS file saved at our server. I want to load CSS from a URL. I have tried many ways but it didn't work for me. Though I am able to insert CSS from the same URL in UIWebView in Objective C code but I am facing issue while trying to achieve the same in WKWebView in SWIFT. I think I am doing some syntax mistake while writing the HTML tag. Please help me out
Here is the code of Objective C:
NSString *html = [NSString stringWithFormat:@"<link type=\"text/css\" href=\"%@\" rel=\"stylesheet\" /> %@<br>", htmlData.cssStr,[htmlData.contentsArr objectAtIndex:slideNo]];
NSLog(@"html .%@", html);
[webview loadHTMLString:html baseURL:nil];
htmlData.cssStr : It is a weblink
As in most of the solution CSS is inserted in SWIFT in func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!). So I am also calling insertContentsOfCSSFile from didFinish of WKWebView. How I tried in SWIFT is :
func insertContentsOfCSSFile(into webView: WKWebView) {
let cssString = try! String(contentsOf: URL(string: self.htmlData.cssStr)!).trimmingCharacters(in: .whitespacesAndNewlines)
print("cssString", cssString)
let jsString = "var style = document.createElement('style'); style.innerHTML = '\(cssString)'; document.head.appendChild(style);"
webView.evaluateJavaScript(jsString, completionHandler: nil)
}