Environment: OpenURL
@Environment(\.openURL) allows you to open URLs from your SwiftUI views.
What is @Environment(\.openURL)?
@Environment(\.openURL) is a property wrapper that provides a way to open URLs in your SwiftUI application. It gives you access to the OpenURL environment value, which you can use to present a URL in the appropriate way for the current platform.
struct ContentView: View {
@Environment(\.openURL) var openURL
var body: some View {
Button("Open Website") {
openURL(URL(string: "https://wesleydegroot.nl")!)
}
}
}
Custom OpenURLAction
You can also set a custom OpenURLAction for your views. This allows you to define how URLs should be handled when they are opened.
struct ContentView: View {
var body: some View {
Text(.init("Visit https://wesleydegroot.nl or [Play a sound](play://sound)"))
.environment(\.openURL, OpenURLAction { url in
if let scheme = url.scheme {
if scheme == "play" {
// MusicPlayer.play(url)
return .handled
}
}
return .systemAction
})
}
}
Wrap up
Opening URLs in SwiftUI is made easy with @Environment(\.openURL). This powerful property wrapper allows you to handle URL actions seamlessly across different platforms.
Resources:
-
https://developer.apple.com/documentation/swiftui/environment
-
https://developer.apple.com/documentation/swiftui/environmentvalues/openurl
-
https://developer.apple.com/documentation/swiftui/openurlaction
Read more
- Contact Provider Extension • 9 minutes reading time.
- Enhancing SwiftUI with CachedAsyncImage • 3 minutes reading time.
- Exploring the .inspector Modifier in SwiftUI • 3 minutes reading time.
Share
Share Bluesky Mastodon Twitter LinkedIn Facebook