Wesley de Groot's Blog
Handle hyperlinks in SwiftUI

Back

Handle hyperlinks in SwiftUI

If you have a SwiftUI application and you present text with a URL, have you notices how the URL is being opened by Safari and not an in-app browser, and want to change that?

What is OpenURLAction?

An action that opens a URL.
OpenURLAction can be used to create your own handler for opening url's in SwiftUI, this makes it possible to use your own (in-app) WebView or transform the url before you open it in a external browser.

OpenURLAction requires a return statement with an appropiate value, in the (psuedo) codeblock below you can see which results are possible and what their meaning is.

struct OpenURLAction.Result {
    /// The handler did handle the URL.
    let handled

    /// The handler discarded the URL.
    let discarded

    /// The handler asks the system to open the original URL.
    let systemAction

    /// The handler asks the system to open the modified URL.
    let systemAction(let URL)
}

Use Case: Simple url handler

requires you to have a function called handleURL()

/// Basic example
Text("Visit [my Blog](https://www.wesleydegroot.nl) for more details.")
    .environment(\.openURL, OpenURLAction { url in
        handleURL(url) // Define this method to take appropriate action.
        return .handled
    })

Use Case: Simple url handler

requires you to have a function called handleURL()

struct SafariURL: Identifiable {
    let id = UUID()
    let url: URL
}

struct ContentView: View {
    @State
    var safariURL: SafariURL?

    var body: some View {
        Text("Visit [my Blog](https://www.wesleydegroot.nl) for more details.")
            .environment(\.openURL, OpenURLAction { url in
                safariURL = SafariURL(url: url)
                return .handled
            })
            .sheet(item: $safariURL, content: { safariURL in
                SafariView(url: safariURL.url)
            })
    }

    func handleURL(url: URL) {
    /// open SFSafariViewController
    }
}

Conclusion

OpenURLAction is a great way to handle URL's in SwiftUI, it allows you to create your own handler for URL's and decide what to do with them.

Resources:

https://developer.apple.com/documentation/swiftui/openurlaction

x-twitter mastodon github linkedin discord threads instagram whatsapp bluesky square-rss sitemap