how to open safari in my swift program

I'm developing a cocoa app runs on macOS(not iOS). And I want to open an Advertisement Web Page while users click the 'Show Advertisement' button.

My Question is: how to open a url in the system's default browser(like safari) through swift code in my app.

And there must be a way to call local browser through swift code, because the in app 'WeChat', when we click a link in that app, the system will open a safari browser and show the content of the link. My question is: how?

Thanks for your help, Best Regards.
Yours,
Alex.Zhang

Replies

You should try this:

Code Block
if let url = URL(string: "some url")
UIApplication.shared.open(url)
}


See: https ://www.hackingwithswift .com/example-code/system/how-to-open-a-url-in-safari
for some additional information.
Thanks a lot, you did me a great favor.
Dear friend,
It works in iOS, but how to do it on Cocoa(macOS Application)?
There is no UIApplication, and no open functions on NSApplication.shared.
How to open safari in Cocoa application?

For MacOS, the call is a bit different, use NSWorkspace

Code Block
if let url = URL(string: "https://www.apple.com/fr/") {
NSWorkspace.shared.open(url)
}

  • Thanks a lot, it helped)

Add a Comment