HowTo —— Handling Universal Links with onOpenURL

Published on

Get weekly handpicked updates on Swift and SwiftUI!

SwiftUI 2.0, with its new coding architecture (Life Cycle SwiftUI App), introduces onOpenURL for handling Universal Links. Unlike solutions in AppDelegate or SceneDelegate, onOpenURL is a view modifier, allowing you to register your app’s URL handling mechanism on any View. For information on creating a URL Scheme for your app, refer to Apple’s official documentation.

Basic Usage

   Text("Hello World")
.onOpenURL { url in
    // Do something

Sample Code

First, set up the URL in the project


import SwiftUI

struct ContentView: View {
    @State var tabSelection: TabSelection = .news
    @State var show = false
    var body: some View {
        TabView(selection: $tabSelection){
                .tabItem { Image(systemName: "newspaper") }
                .tabItem { Image(systemName: "music.quarternote.3") }
                .tabItem { Image(systemName: "dial.max") }
        .sheet(isPresented: $show) {
            Text("URL call parameters incorrect")
        .onOpenURL { url in
            let selection =
            switch selection {
            case "news":
                tabSelection = .news
            case "music":
                tabSelection = .music
            case "settings":
                tabSelection = .settings
                show = true

enum TabSelection: Hashable {
    case news, music, settings

macOS currently does not support this, but it is expected to be provided in the official release.

Special Notes

  • onOpenURL will only respond when the project uses the SwiftUI App method to manage the Life Cycle.

  • Multiple onOpenURL modifiers can be added to the code, registered on different Views. When accessed via URL, each closure will respond. This allows you to make adjustments specific to different Views.

Explore weekly Swift highlights with developers worldwide

Buy me a if you found this article helpful