How to pass text from a textField to Google Search from an iOS app? [closed]

孤街浪徒 提交于 2019-12-06 16:57:02

问题


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


来源:https://stackoverflow.com/questions/48681240/how-to-pass-text-from-a-textfield-to-google-search-from-an-ios-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!