即使我的默认浏览器不是 Safari,如何在 macOS 中使用 Swift 在 Safari 中打开 url?
How to open a url in safari even if my default browser is not Safari using Swift in macOS?
我试图在 Safari 中打开 url,即使我的默认浏览器设置为 Google Chrome。我怎么做?我正在使用以下代码,但它仅在默认浏览器中打开 url。
let requiredURL = URL(string: "https://www.google.com)")!
NSWorkspace.shared.open(requiredURL)
我是否必须使用以下功能:
NSWorkspace.shared.open(urls: [URL], withApplicationAt: URL, options: NSWorkspace.LaunchOptions, configuration: [NSWorkspace.LaunchConfigurationKey : Any])
如果是,我该如何实施?
您可以使用在 macOS 11
中已弃用的 NSWorkspace open method
let url = URL(string: "https://www.google.com")!
NSWorkspace.shared.open([url], withAppBundleIdentifier: "com.apple.safari", options: .default, additionalEventParamDescriptor: nil, launchIdentifiers: nil)
或替换 method(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)
}
我试图在 Safari 中打开 url,即使我的默认浏览器设置为 Google Chrome。我怎么做?我正在使用以下代码,但它仅在默认浏览器中打开 url。
let requiredURL = URL(string: "https://www.google.com)")!
NSWorkspace.shared.open(requiredURL)
我是否必须使用以下功能:
NSWorkspace.shared.open(urls: [URL], withApplicationAt: URL, options: NSWorkspace.LaunchOptions, configuration: [NSWorkspace.LaunchConfigurationKey : Any])
如果是,我该如何实施?
您可以使用在 macOS 11
中已弃用的 NSWorkspace open methodlet url = URL(string: "https://www.google.com")!
NSWorkspace.shared.open([url], withAppBundleIdentifier: "com.apple.safari", options: .default, additionalEventParamDescriptor: nil, launchIdentifiers: nil)
或替换 method(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)
}