How do I Setup my UISearchBar connected to my UIWe

2019-09-01 06:06发布

How do I Setup my UISearchBar connected to my UIWebView to be able to search on google with a word instead of a url. For example search apple instead of http://www.apple.com

Heres my code so far

import UIKit
import WebKit

class ViewController: UIViewController, UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!

@IBOutlet weak var webView: UIWebView!



 func searchBarSearchButtonClicked(searchBar: UISearchBar!) {

    searchBar.resignFirstResponder()
    var text = searchBar.text
    var url = NSURL(string: text)  //type "http://www.apple.com"
    var req = NSURLRequest(URL:url)
    self.webView!.loadRequest(req)
}

override func viewDidLoad() {
    super.viewDidLoad()

    let url = NSURL(string: "http://google.com")
    let request = NSURLRequest(URL: url)
    webView.loadRequest(request)

    self.searchBar.delegate = self
     }
}

2条回答
啃猪蹄的小仙女
2楼-- · 2019-09-01 06:23

This is how I implemented this using Swift 3 and a TextField for input. Hope it helps someone.

 func search(){
        var searchTerms = self.searchTextField.text!
        searchTerms = searchTerms.replacingOccurrences(of: " ", with: "+")

        let urlString = "http://www.google.com/search?q=\(searchTerms)"
        let url = URL(string: urlString)

        let request = URLRequest(url: url!)
        webView.loadRequest(request)
        self.searchTextField.endEditing(true)//dismiss keyboard
    }
查看更多
祖国的老花朵
3楼-- · 2019-09-01 06:44

You need to append the string from your UISearchBar to the following string http://www.google.com/search?q= then create a URL from that. Append the string like this

text = text.stringByReplacingOccurrencesOfString(" ", withString: "+");
var url = NSURL(string: "http://google.com/search?q=".stringByAppendingString(text));

So a search for apple would look like http://www.google.com/search?q=apple

查看更多
登录 后发表回答