Swift on macOS: open Chrome with a URL as parameter
Asked Answered
U

1

4

I'd like to open Chrome with a specific URL from my macOS app.

I'm trying it like this, but unfortunately it doesn't work. Chrome is opened, but not with the given URL String.

let configuration = NSWorkspace.OpenConfiguration()
configuration.arguments = [url.absoluteString]
let appUrl = URL(fileURLWithPath: "/Applications/Google Chrome.app")
NSWorkspace.shared.openApplication(at: appUrl,
    configuration: configuration,
    completionHandler: nil)

open() does not help me in this case, as I don't want to open the standard browser.

Help is highly appreciated!

Uxorious answered 5/5, 2020 at 16:5 Comment(0)
U
5

I solved it.

NSWorkspace.shared.open([url],
    withApplicationAt: URL(fileURLWithPath: "/Applications/Google Chrome.app"),
    configuration: configuration)

did the trick

Uxorious answered 5/5, 2020 at 22:16 Comment(3)
You should use urlForApplication(withBundleIdentifier:) to obtain the URL rather than hard-coding it. A bundle ID is a much safer way to identify an app than its name or path, which can be changed by the user.Horick
@KenThomases Thanks for your suggestion. I fully agree.Uxorious
Silently fails for me on M1/Ventura/Xcode 14.3Lamentation

© 2022 - 2024 — McMap. All rights reserved.