-->

How to pass text from a textField to Google Search

2020-08-01 02:39发布

问题:

I would like to pass a string to the Google search from my iOS app, so as to enable me to fetch the results in Safari.

回答1:

You can do something like this:

var query = "hello world"
query = query.replacingOccurrences(of: " ", with: "+")
var url = "https://www.google.co.in/search?q=" + query
UIApplication.shared.open(URL(string: url)!, options: [:], completionHandler: nil)

Replace query with your search string.



回答2:

If you use your own web view (which you specified in your comment before you changed it to something completly different), you could use the WKWebView and URLRequest to load and display the data. Don't forget to escape the query string, something like:

@IBOutlet weak var webView: WKWebView!

func startSearch() {

    var textToSearch = "the answer to everything"
    // if there are spaces or other special characters,
    // you'll have to escape them:
    let allowedCharacters = NSCharacterSet.urlFragmentAllowed

    guard let  encodedSearchString  = textToSearch.addingPercentEncoding(withAllowedCharacters: allowedCharacters)  else { return }

    let queryString = "https://www.google.de/search?q=\(encodedSearchString)"
    guard let queryURL = URL(string: queryString) else { return }

    let myRequest = URLRequest(url:queryURL)
        webView.load(myRequest)
}