如何在浏览器项目中显示用户谷歌搜索引擎结果

时间:2018-02-17 11:48:07

标签: swift uiwebview

我正在使用带有swift for iPhone,iPad的UIWebView实现一个浏览器。一切正常,但问题是,当用户键入错误或未完成他们喜欢的网站的URL时,它似乎崩溃并且不会呈现任何内容。所以如果浏览器找不到所请求的页面,我想以某种方式做,然后它会自动在谷歌搜索引擎上搜索那个确切的单词并在浏览器中显示结果。 如果需要,这是我的代码。 感谢任何帮助

 func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    //let urlString:String = urlTextField.text!
    var urlString: String = urlTextField.text!

    if !urlString.starts(with: "http://") && !urlString.starts(with: "https://") {
        urlString = "http://\(urlString)"
    }

    let url:URL = URL(string: urlString)!
    let urlRequest:URLRequest = URLRequest(url: url)
    webView.load(urlRequest)

    textField.resignFirstResponder()

    let path: String = url.path
    let ext: String = URL(fileURLWithPath: path ).pathExtension
    print(ext as Any)

    return true

} 

1 个答案:

答案 0 :(得分:3)

您可以添加一项检查来验证您的urlString是否包含www,如果不是,您可以设置" https://www.google.com/search?q="你的文字网址:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    guard let urlString = urlTextField.text else { return true }

    if urlString.starts(with: "http://") || urlString.starts(with: "https://") {
        loadUrl(urlString)
    } else if urlString.contains(“www”) {
        loadUrl("http://\(urlString)")   
    } else { 
        searchTextOnGoogle(urlString)
    }

    textField.resignFirstResponder()
    //...

    return true
} 

func loadUrl(_ urlString: String) {
    guard let url = URL(string: urlString) else { return }

    let urlRequest = URLRequest(url: url) 
    webView.load(urlRequest)
}

func searchTextOnGoogle(_ text: String) {
    // check if text contains more then one word separated by space 
    let textComponents = text.components(separatedBy: " ") 

    // we replace space with plus to validate the string for the search url
    let searchString = textComponents.joined(separator: "+") 

    guard let url = URL(string: "https://www.google.com/search?q=" + searchString) else { return }

    let urlRequest = URLRequest(url: url) 
    webView.load(urlRequest)
}