Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OSX Swift open URL in default browser

How to open a url in system default browser by using Swift as programming language and OSX as plattform.

I found a lot with UIApplication like

UIApplication.sharedApplication().openURL(NSURL(string: object.url))

but this works just on iOS and not on OSX

And the Launch Services, I found has no examples for swift and there is a lot deprecated for OSX 10.10

Any help welcome - thanks.

like image 895
user2929462 Avatar asked Nov 02 '14 21:11

user2929462


2 Answers

Swift 3 or later

import Cocoa

let url = URL(string: "https://www.google.com")!
if NSWorkspace.shared.open(url) {
    print("default browser was successfully opened")

}
like image 169
Leo Dabus Avatar answered Nov 09 '22 22:11

Leo Dabus


For MacOS, you can use this:

let url = URL(string: "https://www.stackoverflow.com")!
NSWorkspace.sharedWorkspace().openURL(url))

For iOS, you can use the following:

let url = NSURL(string: "https://google.com")!
UIApplication.sharedApplication().openURL(url)

You have to unwrap NSURL.

like image 53
Connor Knabe Avatar answered Nov 10 '22 00:11

Connor Knabe