How to pass text from a textField to Google Search

2020-08-01 02:18发布

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.

2条回答
乱世女痞
2楼-- · 2020-08-01 02:38

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)
}
查看更多
Explosion°爆炸
3楼-- · 2020-08-01 02:45

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.

查看更多
登录 后发表回答