0
votes

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)

}
1

1 Answers

0
votes

In your HTML, you need parent tags like HTML, Head, Body etc. Please try the below code. and the changes as you wish.

NSString *bodyTag = [NSString stringWithFormat:@"<body><div id='main-div'>%@</div></body>",[htmlData.contentsArr objectAtIndex:slideNo]]; // Pass Var -> body value
NSString *css = [NSString stringWithFormat:@"<link type=\"text/css\" href=\"%@\" rel=\"stylesheet\" />", htmlData.cssStr];

NSString *htmlString = [NSString stringWithFormat:@"<!DOCTYPE html><html xmlns='https://www.w3.org/1999/xhtml'><head>  <meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><meta name = \"viewport\" content = \"width = 320, initial-scale = 1.0, user-scalable = yes\"><link href=\"%@\" rel=\"stylesheet\" type=\"text/css\" /></head>%@</html>", css, bodyTag]; // Pass Var -> css url and bodyTag