[英]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
我试图将预附加的字符串作为URL请求传递,并且不断收到错误消息: fatal error: unexpectedly found nil while unwrapping an Optional value
This error points to the line: let searchTerm = "http://google.com/#q="+textField.text!
此错误指向以下行: let searchTerm = "http://google.com/#q="+textField.text!
ViewController.swift 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 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)
,使用防护来展开您可选的textfield文本属性,并使用允许查询的字符集向字符串中添加转义百分比。
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))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.