1

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.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • Do you mean something like this: Swift Open Link in Safari https://stackoverflow.com/questions/25945324/swift-open-link-in-safari – Andreas Oetjen Feb 08 '18 at 08:58
  • No, based on the String, I have to fetch results from google search –  Feb 08 '18 at 09:03
  • So, you don't want to display/fetch the results in safari, you simply want to somehow parse the query results (HTML) in your code, without displaying them? – Andreas Oetjen Feb 08 '18 at 09:04
  • Yes i want to display the results in the browser itself, which is exactly like using Google Search. –  Feb 08 '18 at 09:08

2 Answers2

5

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)
}
Andreas Oetjen
  • 9,889
  • 1
  • 24
  • 34
4

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.

Aryan Sharma
  • 625
  • 2
  • 9
  • 24