0

I am just starting on IOS/SWIFT and I am running though some basic tasks...

I have seem to run across an issue I can not figure out nor understand the issue.

I want to display the webpage in my web view but the optional value is returning NIL but holds a value line before...

    if let address = webSite {
        let webURL = URL(string: address) //webURL=="google.com" at this point 
        let urlRequest = URLRequest(url: webURL!)
        webView.loadRequest(urlRequest)
    }

urlRequest is NILL after trying the URLRequest..even tho webURL holds a value of "google.com" Which then results in the loadRequest crashing with the error

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

I believe I understand the concept of the optional value that it will return NILL if it holds no value but I can produce the value of "google.com" at URL call.

workingxx
  • 226
  • 4
  • 16

2 Answers2

0

Please unwrap optional webURL like below,

if let address = webSite, let webURL = URL(string: address) {
    let urlRequest = URLRequest(url: webURL)
    webView.loadRequest(urlRequest)
}

Also verify webView is properly initialized or connected in storyboard

Kamran
  • 14,987
  • 4
  • 33
  • 51
0

Its better to check whether URL is successfully created or not?. For your case it is for sure that URL(string: address) is not able to create a valid URL and force wnwrapping (putting ! mark) crashing the app.

Update your code as:

   if let address = webSite, let webURL = URL(string: address) {
        let urlRequest = URLRequest(url: webURL)
        webView.loadRequest(urlRequest)
    }
Ankit Jayaswal
  • 5,549
  • 3
  • 16
  • 36
  • This is still giving me a "Fatal error: Unexpectedly found nil while unwrapping an Optional value" on the loadRequest call – workingxx Apr 12 '18 at 21:46