5

I am trying to open a url in Safari even if my default browser is set to Google Chrome. How do I do that? I am using the following code, but it opens the url in the default browser only.

let requiredURL = URL(string: "https://www.google.com)")!
NSWorkspace.shared.open(requiredURL)

Do I have to use the following function:

NSWorkspace.shared.open(urls: [URL], withApplicationAt: URL, options: NSWorkspace.LaunchOptions, configuration: [NSWorkspace.LaunchConfigurationKey : Any])

If so, how do I implement it?

onetrueshady
  • 175
  • 1
  • 10
  • i have found what you are looking for not the best approch but it will help you out https://stackoverflow.com/a/57496854/10585521 – Abdul Saboor Nov 17 '20 at 06:21
  • the shell process works except that it only opens the host url. For example, if i am trying to search something on google, the url should open the search result. However, using this method, it only manages to open www.google.com. Not the search within google. – onetrueshady Nov 17 '20 at 06:57
  • what i the link you want to open ? is there a chance you are are providing the wrong url ? – Abdul Saboor Nov 17 '20 at 07:06

1 Answers1

1

You can use NSWorkspace open method which has been deprecated in macOS 11

let url = URL(string: "https://www.google.com")!

NSWorkspace.shared.open([url], withAppBundleIdentifier: "com.apple.safari", options: .default, additionalEventParamDescriptor: nil, launchIdentifiers: nil)

Or the replacement method (macOS 10.15 or later)

do {
    let safariURL = try FileManager.default.url(for: .applicationDirectory, in: .localDomainMask, appropriateFor: nil, create: false).appendingPathComponent("Safari.app")
    NSWorkspace.shared.open([url], withApplicationAt: safariURL, configuration: .init()) { (runningApp, error) in
        print("running app", runningApp ?? "nil")
    }
} catch {
    print(error)
}
   
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • This solution works fine except that it sometimes opens the link in a new tab and sometimes in a new window entirely. Is there any way to open in a new tab only? – onetrueshady Nov 30 '20 at 06:53
  • This is failing for me silently on M1 MacBook Air/Ventura/Xcode 14.3 – hippietrail Aug 29 '23 at 17:32