1

I want to open google search for any given string, here is my code, but it does not open the search for the given string for example.

let s = "A long-running line of '80s ads urged potential pizza customers to “avoid” what?"
let search = s.replacingOccurrences(of: " ", with: "+")



if let url = URL(string: "https://www.google.com/search?q=\(search)"), NSWorkspace.shared.open(url) {
        print("default browser was successfully opened")

    }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Jay.Rana
  • 59
  • 7

1 Answers1

1

There are other characters in your string that need to be escaped properly, not just the spaces.

let s = "A long-running line of '80s ads urged potential pizza customers to “avoid” what?"
let search = s.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

if let search = search, let url = URL(string: "https://www.google.com/search?q=\(search)"), NSWorkspace.shared.open(url) {
    print("default browser was successfully opened")
} else {
    print("Can't create search URL with \(search)")
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579