Open a URL when tapping a SwiftUI Button


In this tutorial, you are going to learn how to open a URL or link when tapping a Button in SwiftUI.

We can perform in two ways. In the first example, we are going to use the SwiftUI Button control and keep the required code in the button action. In the second example, we are going to use the Link control which will make our code easier.

Open an URL when the Button tap action triggers

Below is our Swift program for SwiftUI to open an URL after clicking the button built with Button control:

          
          Button(action: {
              if let url = URL(string: "https://swiftspeedy.com/") {
                 UIApplication.shared.open(url)
              }
          }) {
              Text("Go to SwiftSpeedy")
          }
          

As you can see, it is just a regular SwiftUI Button. Inside the button action, we declare our URL https://swiftspeedy.com/ and pass it to the open() method. Clicking the button opens our URL in the app.

Using the Link control (A more easy way)

The new version of iOS comes with a more convenient way to open a URL in SwiftUI. It comes with Link control that can help us to open a link just with one line of code.

The Link is just like a button, but it is only used to open a link.

Below is how we can open the link https://swiftspeedy.com/ on clicking the Link button:

Link("Go to SwiftSpeedy", destination: URL(string: "https://swiftspeedy.com/")!)

Well, just like a Button control, you can provide padding, background color, foreground color and a lot:

      Link("Go to SwiftSpeedy", destination: URL(string: "https://swiftspeedy.com/")!)
          .padding().background(Color.green)
          .foregroundColor(Color.white)

The above program will show a button as you can see below:

SwiftUI Button

As you can see, we can design our Link control just like a Button control.

Clicking the Link will open the link or URL just like we show in previous examples.