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
Post a Comment