Updated for Xcode 14.2
When your user taps a URL shown inside a SwiftUI Text
or Link
view, it will open in Safari by default. However, you can customize this behavior by replacing the openURL
environment key – you might want to handle the link entirely, or perhaps pass it back to the system to open once your custom action completes.
For example, this code adjusts both a Link
and a Text
view so that all URLs are sent to a handleURL()
method to be acted on:
struct ContentView: View {
var body: some View {
VStack {
Link("Visit Apple", destination: URL(string: "https://apple.com")!)
Text("[Visit Apple](https://apple.com)")
}
.environment(\.openURL, OpenURLAction(handler: handleURL))
}
func handleURL(_ url: URL) -> OpenURLAction.Result {
print("Handle \(url) somehow")
return .handled
}
}
Download this as an Xcode project
As you can see, handleURL()
returns a OpenURLAction.Result
value of .handled
, which means the method accepted the link and acted on it. There are alternatives:
.discarded
if you mean you weren’t able to handle the link..systemAction
if you want to trigger the default behavior, perhaps in addition to your own logic..systemAction(someOtherURL)
if you want to open a different URL using the default behavior, perhaps a modified version of the URL that was originally triggered.Remember, links will use your app’s accent color by default, but you can change that using the tint()
modifier:
Text("[Visit Apple](https://apple.com)")
.tint(.indigo)
Download this as an Xcode project
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Link copied to your pasteboard.