Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: How do I make a button open a URL in safari?

I want a button inside my app, that will open safari and a specific URL address. How do I do this? UIApplication.sharedApplication doesn't seem to work in SwiftUI.

This is my first question here. Please give feedback if I did something wrong 😸

like image 952
Marcus Ziadé Avatar asked Oct 31 '19 12:10

Marcus Ziadé


Video Answer


2 Answers

iOS 14.0+

Using Link:

Link("Some label", destination: URL(string: "https://www.mylink.com")!)

Older versions

Button(action: {
    if let url = URL(string: "https://www.mylink.com") {
       UIApplication.shared.open(url)
    }
}) {
    Text("Some label")
}
like image 178
cbear84 Avatar answered Oct 04 '22 09:10

cbear84


If you are using a SceneDelegate you can handle URL addresses using the following:

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {

    guard let url = URLContexts.first?.url else {
        return
    }

    //Handle URL here
}

From there you can call openURL like you normally would:

UIApplication.shared.open(url, options: [:], completionHandler: nil)
like image 41
jfuellert Avatar answered Oct 04 '22 09:10

jfuellert