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

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

Sample Code

First, set up the URL in the project

URL

Swift
import SwiftUI

struct ContentView: View {
    @State var tabSelection: TabSelection = .news
    @State var show = false
    var body: some View {
        TabView(selection: $tabSelection){
            Text("News")
                .tabItem { Image(systemName: "newspaper") }
                .tag(TabSelection.news)
            Text("Music")
                .tabItem { Image(systemName: "music.quarternote.3") }
                .tag(TabSelection.music)
            Text("Settings")
                .tabItem { Image(systemName: "dial.max") }
                .tag(TabSelection.settings)
        }
        .sheet(isPresented: $show) {
            Text("URL call parameters incorrect")
        }
        .onOpenURL { url in
            let selection = url.host
            switch selection {
            case "news":
                tabSelection = .news
            case "music":
                tabSelection = .music
            case "settings":
                tabSelection = .settings
            default:
                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.

Weekly Swift & SwiftUI insights, delivered every Monday night. Join developers worldwide.
Easy unsubscribe, zero spam guaranteed