1

I am using mywebview.loadHTMLString(htmlCode, baseURL: nil) but it's not working properly, means it doesn't support javascript and css, it only displayed the text inside that html code.

I am getting the html code from api and store it into the String data type and need to pass to the webview.

I have found one more thing webview.load() but it shows me "cannot convert value of type 'String' to expected argument type 'Data'.

Does anyone know how to solve this problem?

This is my simple demo html code, which i wanted to display.But i am getting the color which i have used in above html.

<!doctype html>
<html>
<head>
 <title></title>
</head>
<body>
<p>This is a demo html code, <span style="background-color:#FF0000;">which i wanted to display on UIwebview</span> .</p>

<p>But <span style="color:#800080;">it&#39;s wokring</span> properly if i save this code as a<span style="color:#0000FF;"> .html</span> extension then works perfect.</p>
</body>
</html>
Sanket P
  • 23
  • 1
  • 8

4 Answers4

0

Don't provide baseUrl as nil, Provide the URL where js, css and other files are located.

Rupendra
  • 89
  • 1
  • 2
  • He mentioned getting the `htmlString` from the API. It should be fine to provide `baseURL` nil. – Kamran Apr 13 '18 at 12:02
  • Even if html string is getting generated at server, the js and css dependencies must be present somewhere (may be on the same server), so UIWebView will need that path as baseURL to refer to those files. – Rupendra Apr 13 '18 at 12:07
  • I have added the sample html code in my post. please check it. – Sanket P Apr 13 '18 at 13:39
0

According to the documentation webview.load() expects data not a string. You can convert your html string to data:

guard let data = yourString.data(using: .utf8) else {
    print("Couldn't convert string to data")
    return
}

webview.loadHTMLString() should load html as a string. Your base url property is probably causing the issue. Take a look at this answer it's a working example of webview.loadHTMLString().

Lloyd Keijzer
  • 1,229
  • 1
  • 12
  • 22
0

Use this code it's working for you

let webView = UIWebView()
webView.loadHTMLString("<html><body><p>Hello!</p></body></html>", baseURL: nil)

(OR)

let webView = UIWebView()
webView.loadHTMLString("\(htmlcode)", baseURL: nil)
0

Maybe you did not escape all characters correctly. Please post the full code of what you tried. For example, if you put the following tag in a string:

<span style="background-color:#FF0000;">

You need to do it like

let span = "<span style=\"background-color:#FF0000;\">"

You can then put together your HTML string like this:

let html = "<!DOCTYPE html>" +
        "<html>" +
        "<head>" +
        "<meta charset=\"UTF-8\">"

and so on. To load the HTML string just use

webView.loadHTMLString(html, baseURL: nil)
sundance
  • 2,930
  • 1
  • 20
  • 25