How do I support deep links in SwiftUI with Swift?

Deep linking in SwiftUI allows users to navigate directly to specific content within your app via a URL. This can be particularly useful for providing a seamless user experience and boosting engagement.

Here’s how you can implement deep linking in your SwiftUI application:

// Import necessary modules import SwiftUI // Define a model for your deep link struct DeepLink: Hashable { var id: String } // Define your main view struct ContentView: View { @State private var selectedDeepLink: DeepLink? var body: some View { NavigationView { VStack { NavigationLink(destination: DetailView()) { Text("Go to Detail View") } } .onOpenURL(perform: handleDeepLink) } } func handleDeepLink(_ url: URL) { // Handle the deep link URL if let components = URLComponents(url: url, resolvingAgainstBaseURL: false) { if let id = components.queryItems?.first(where: { $0.name == "id" })?.value { selectedDeepLink = DeepLink(id: id) } } } } // Define a detail view to display based on the deep link struct DetailView: View { var body: some View { Text("This is the Detail View") } } // Main app struct @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }

deep linking SwiftUI iOS development mobile app navigation URL handling