问题
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
}
}
回答1:
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
回答2:
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
}
来源:https://stackoverflow.com/questions/26447880/how-do-i-setup-my-uisearchbar-connected-to-my-uiwebview-to-be-able-to-search-on