@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: