NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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)")
    .tint(.indigo)

Download this as an Xcode project

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
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!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.