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.

I'm really looking forward to hearing your thoughts! Please Leave Your Comments Below to share your views and insights.

Fatbobman(东坡肘子)

I'm passionate about life and sharing knowledge. My blog focuses on Swift, SwiftUI, Core Data, and Swift Data. Follow my social media for the latest updates.

You can support me in the following ways