0

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!))
Kerberos
  • 4,036
  • 3
  • 36
  • 55
chevi99
  • 123
  • 1
  • 2
  • 17
  • `|` is an invalid character, you must see which character the java server waits to then split the users id – Kerberos Aug 27 '18 at 19:53
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Cristik Aug 27 '18 at 19:56
  • @Kerberos the java server uses | to split it parameters i add – chevi99 Aug 27 '18 at 19:56
  • Ok, try to use this link: `https://myapp.mydomain.com/GameAPI/index.jsp?user=0202020767%70202020767` – Kerberos Aug 27 '18 at 20:02

2 Answers2

2

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")
}
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • it's not crashing anymore but the webview is always blank. I tried to print url and i had something like this https%3A%2F%2Fmyapp.mydomain.com%2FGameAPI%2Findex.jsp%3Fuser=0202020767%7C0202020767 – chevi99 Aug 27 '18 at 19:47
  • I modified my code to only escape the params. Let's see that happens! – Michael Dautermann Aug 27 '18 at 20:50
  • Your solution worked but I have to force unwrapped escapedParam. Thanks!!! – chevi99 Aug 28 '18 at 09:12
0

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")
}
Dogan Altinbas
  • 268
  • 2
  • 11