Search code examples
swiftwebviewbase-url

Trouble using loadHTMLString in Swift


I'm trying to make an app that will scrape data off of a site then load it. I've managed to scrape it with:

let task = URLSession.shared.dataTask(with: myURL) {(data, response, error) in

de-encode it with:

let newStr = String(data: data!, encoding: .utf8)

and I'm trying to load it with:

webView.loadHTMLString(newStr, baseURL:"")

But if I leave it blank it just crashes and gives this error:

fatal error: unexpectedly found nil while unwrapping an Optional value

I'm not sure what to set the baseURL as because I'm creating the string in app.

What should I set the baseURL to?


Solution

  • Instead of using the empty string "", just use nil as the baseURL.

    Edit:

    Now that you've determined that your webView is nil, the rest should be easy! Go to your code where you initialize the webView, add error messages as appropriate to see why it isn't succeeding. (a nil webView means either it failed initialization, or you never initialized it...)