Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios searchBarSearchButtonClicked url返回nil_Ios_Swift - Fatal编程技术网

Ios searchBarSearchButtonClicked url返回nil

Ios searchBarSearchButtonClicked url返回nil,ios,swift,Ios,Swift,我试图用搜索栏设置一个简单的tableview,但在我的函数SearchBarSearchButton中,单击了url常量return nil,因此无法加载urlRequest 谢谢你的帮助 func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { var text = searchBar.text text = text?.replacingOccurrences(of: " ", with: "+")

我试图用搜索栏设置一个简单的tableview,但在我的函数SearchBarSearchButton中,单击了url常量return nil,因此无法加载urlRequest

谢谢你的帮助

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    var text = searchBar.text
    text = text?.replacingOccurrences(of: " ", with: "+")
    let url = URL(string: "https://www.google.com/#q=\(text)")
    let req = URLRequest(url: url! as URL)
    wv.loadRequest(req as URLRequest)
}

您的问题是
“q=\(text)”
变为
“q=可选(此处的文本)”
,因为
文本
字符串?
而不是普通的
字符串。可以将其展开,也可以使用默认值
??“”
要避免它:

let url = URL(string: "https://www.google.com/#q=\(text ?? "")")

此外,为了在URL中使用参数,您必须对参数进行URL编码:

let searchQuery = "What's the meaning of life and everything"
let encodedQuery = searchQuery.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let url = URL(string: "https://www.google.com/#q=\(encodedQuery)")!

您还可以使用
URLComponents
类组成一个安全的URL

let searchQuery = "What's the meaning of life and everything"

var urlComponents = URLComponents(string: "https://www.google.com")
urlComponents?.queryItems = [
    URLQueryItem(name: "q", value: searchQuery)
]

let url = urlComponents?.url!

为了避免运行时崩溃,最好不要使用强制展开选项
,并使用
如果let
保护let
将其展开:

if let url = urlComponents?.url {
    let req = URLRequest(url: url)
    wv.loadRequest(req)
}

您输入了哪个文本?它应该与您的文本有关,因为let url=url(字符串:)不会使用您的代码返回nili-get-url