即使我的默认浏览器不是 Safari,如何在 macOS 中使用 Swift 打开 Safari 中的 URL?

one*_*ady 5 safari macos swift

即使我的默认浏览器设置为 Google Chrome,我也尝试在 Safari 中打开网址。我怎么做?我正在使用以下代码,但它仅在默认浏览器中打开网址。

let requiredURL = URL(string: "https://www.google.com)")!
NSWorkspace.shared.open(requiredURL)
Run Code Online (Sandbox Code Playgroud)

我必须使用以下功能吗:

NSWorkspace.shared.open(urls: [URL], withApplicationAt: URL, options: NSWorkspace.LaunchOptions, configuration: [NSWorkspace.LaunchConfigurationKey : Any])
Run Code Online (Sandbox Code Playgroud)

如果是这样,我该如何实施?

Leo*_*bus 1

您可以使用 NSWorkspace打开方法,该方法已在 macOS 11 中弃用

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

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

或者替换方法(macOS 10.15或更高版本)

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)
}
   
Run Code Online (Sandbox Code Playgroud)