WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

How to customize the way links are opened

Paul Hudson    @twostraws   

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:

  • Use .discarded if you mean you weren’t able to handle the link.
  • Use .systemAction if you want to trigger the default behavior, perhaps in addition to your own logic.
  • Use .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)")

Download this as an Xcode project

Save 50% in my WWDC23 sale.

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.

Save 50% on all our books and bundles!

Similar solutions…

Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.