Search code examples
swiftxcodemacosweb-search

Open google search page for my query using swift (xcode)


I want to open Google search page for a given query using swift. Here is my code that opens the google web page on my default browser but i need it to open search results for a given query. How to go about it? I am new to swift.

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

Solution

  • Try using this code:

    let search = “Example”
    if let url = URL(string: "https://www.google.com.au/search?client=safari&channel=ipad_bm&source=hp&ei=PSrkWqHVDYrc8QXp85zoAw&q=/(search)&oq=example&gs_l=mobile-gws-wiz-hp.3..0l5.58620.59786..60164...0....334.1724.0j2j3j2..........1.......3..41j0i131.SurD5PmVspw%3D"), NSWorkspace.shared.open(url) {
            print("default browser was successfully opened")
        }
    

    The “search” constant would be whatever you want to search. This won’t work for spaces however. For a space you would want to have a “+” in between each word instead of a space.