JDev
JDev

Reputation: 5558

fatal error: unexpectedly found nil while unwrapping an Optional value (cannot force unwrap value of non-optional type 'String')

I am trying to pass a pre-appended String as a URL request and I keep getting the error: fatal error: unexpectedly found nil while unwrapping an Optional value

This error points to the line: let searchTerm = "http://google.com/#q="+textField.text!

ViewController.swift

func textFieldDidUpdate(textField: UITextField) {

    if (textField.text!.rangeOfCharacterFromSet(NSCharacterSet.whitespaceCharacterSet()) != nil) {
        self.webView.hidden = false
        let searchTerm = "http://google.com/#q="+textField.text!
        let request = NSURLRequest(URL: NSURL(string: searchTerm)!)
        self.webView.loadRequest(request)
    }
}

Upvotes: 1

Views: 662

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236260

You should change the method parameter name to func textFieldDidUpdate(sender: UITextField), use guard to unwrap your optional textfield text property and add percent escapes also to your string using query allowed character set.

func textFieldDidUpdate(sender: UITextField) {
    guard
        let text = sender.text,
        query = text.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet()),
        url = NSURL(string: "https://google.com/#q=\(query)")
    else { return }
    webView.hidden = false
    webView.loadRequest(NSURLRequest(URL: url))
}

Upvotes: 5

Related Questions