chevi99
chevi99

Reputation: 143

Why does web view crashes

I'm calling a webpage in WKWebView but it always crashes when I launch the app, with this error message:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value.

My code is below

let param = "https://myapp.mydomain.com/GameAPI/index.jsp?user=0202020767|0202020767"
let url = URL(string: param)
webView.load(URLRequest(url: url!))

At this point the nil is pointing to this code:

webView.load(URLRequest(url: url!))

Upvotes: 0

Views: 504

Answers (2)

Michael Dautermann
Michael Dautermann

Reputation: 89509

I suspect that "|" character in the parameter is messing up your URL.

Try doing this:

let param = "user=0202020767|0202020767"
let escapedParam = param.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let fullURLString = "https://myapp.mydomain.com/GameAPI/index.jsp?\(escapedParam)"
if let url = URL(string: fullURLString) {
    webView.load(URLRequest(url: url))
} else {
    Swift.print("url is nil for some reason")
}

Upvotes: 2

Dogan Altinbas
Dogan Altinbas

Reputation: 451

This is happening, because the url that you have tried to reach could not be resolved.

Also, you better use optional binding rather than forcing unwrap.

Here the code that you can check with valid url:

if let url = URL(string: "your url") {
   webView.load(URLRequest(url: url))

} else {
   print("could not open url, it is nil")
}

Upvotes: 0

Related Questions