Fabrizio
Fabrizio

Reputation: 65

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

I get an error when I press a button on the sideBar stopping here:

webView.scalesPageToFit = true
webView.loadRequest(request)

I would like to ask help to solve the problem. Below is my code of ViewController.swift

import UIKit

class ViewController: UIViewController, UISearchBarDelegate {
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = NSURL(string: "http://www.apple.com")
        let request = NSURLRequest(URL: url!)

        webView.scalesPageToFit = true
        webView.loadRequest(request)
    }

    func searchBarSearchButtonClicked(searchBar: UISearchBar! {
        caricaUrl(searchBar.text)
    }

    func caricaUrl(url: String) {
        let url = NSURL(string: "http://www.google.com/search?q=" + "\(url)")

        let request = NSURLRequest(URL: url!)

        webView.scalesPageToFit = true
        webView.loadRequest(request)
    }

    func didReceiveMemoryWaarning() {
        super.didReceiveMemoryWarning()   
    }


    @IBAction func onBurger() {
        (tabBarController as TabBarController).sidebar.showInViewController(self, animated: true)
    }

}

Upvotes: 4

Views: 5313

Answers (1)

Wiem
Wiem

Reputation: 163

Your web view is an optional value, so you either have to force unwrap it or say that it is an optional when calling it. Your app was trying to force unwrap it, and it came back with nil. That means you can't force unwrap the variable.

So you can change both of these lines in both places they are declared:

webView.scalesPageToFit = true
webView.loadRequest(request)

to these lines:

webView?.scalesPageToFit = true
webView?.loadRequest(request)

The question mark explicitly says that the webView variable is an optional.

Upvotes: 6

Related Questions