Launch Safari (Not Default Browser) at Url in Swift

How to open a url in safari even if my default browser is not Safari using Swift in macOS?

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)
}

How to open a url in Safari instead of the default browser (JavaScript)?

I managed to do this using Swift. I added the following webkit delegate method.

func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
NSWorkspace.shared.open([navigationAction.request.url!], withAppBundleIdentifier: "com.apple.safari", options: .default, additionalEventParamDescriptor: nil, launchIdentifiers: nil)
return nil
}

Can't open a link when the default browser has been changed

For iOS 14+

I suggest to add this to your Info.plist

 <key>LSApplicationQueriesSchemes</key>
<array>
<string>https</string>
</array>

By adding this you can continue to use method canOpenURL(_ url: URL) -> Bool

guard let url = URL(string: "https://example.com") else { return }
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
}

Open non-URL string in Safari (e.g. Search)

You can use x-web-search:// scheme with x-web-search://?[SearchValue].

Sample code:

let urlStr = "x-web-search://?[SearchValue]"
if let url = URL(string: urlStr) {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:]) { didEnd in
print("Did End: \(didEnd)")
}
} else {
print("Can't open URL")
}
} else {
print("Isn't URL")
}


Related Topics



Leave a reply



Submit