Skip to content
DeveloperMemos

Using @Environment and .openUrl to Open Links

iOS, SwiftUI, Development1 min read

Have you ever wanted to include clickable links in your iOS app that open in the device's default browser? If you're building an iOS app using SwiftUI, you're in luck! In this article, we will guide you through the process of using the @Environment property wrapper and the .openUrl method to achieve this functionality.

Opening Links in iOS (SwiftUI)

If you're developing an iOS app using SwiftUI, you can leverage the @Environment property wrapper and the .openUrl method to open links. Here's an example of how you can achieve this in Swift:

1import SwiftUI
2
3struct ContentView: View {
4 @Environment(\.openURL) var openURL
5
6 var body: some View {
7 VStack {
8 Button(action: {
9 if let url = URL(string: "https://example.com") {
10 openURL(url)
11 }
12 }) {
13 Text("Open Link")
14 }
15 }
16 }
17}

In the above example, we use the @Environment(\.openURL) property wrapper to access the openURL function provided by the environment. We then create a Button and specify an action that triggers the opening of a URL when tapped.

Replace "https://example.com" with the actual URL you want to open in your app. When the button is tapped, the provided URL will be opened in the device's default browser.

Alternative Approach: Using UIApplication

Another way to open links in SwiftUI is by utilizing the UIApplication.shared instance. Here's an alternative example:

1import SwiftUI
2import UIKit
3
4struct ContentView: View {
5 var body: some View {
6 VStack {
7 Button(action: {
8 if let url = URL(string: "https://example.com") {
9 UIApplication.shared.open(url)
10 }
11 }) {
12 Text("Open Link")
13 }
14 }
15 }
16}

In this approach, we directly access the shared instance of UIApplication and call the open method with the desired URL. The effect is the same: the provided URL will be opened in the device's default browser when the button is tapped.

Wrap Up

Opening links within mobile applications is an essential feature that enhances user experience and provides seamless integration with external resources. By utilizing the @Environment property wrapper in SwiftUI or using the UIApplication.shared instance, you can easily incorporate this functionality into your SwiftUI apps.