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


i trying pass pre-appended string url request , keep getting error: fatal error: unexpectedly found nil while unwrapping optional value

this error points 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)     } } 

you should change method parameter name func textfielddidupdate(sender: uitextfield), use guard unwrap optional textfield text property , add percent escapes 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)) } 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -