Search code examples
iosxcodeswiftuiwebviewuisearchbar

How do I Setup my UISearchBar connected to my UIWebView to be able to search on google with a word instead of a url using swift


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
     }
}

Solution

  • 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