SwiftUI Navigation Deep Links
SwiftUI Navigation: Deep Links
Handle incoming URLs to navigate directly to content using onOpenURL.
Basic onOpenURL
onOpenURL is used to handle incoming URLs.
Example
import SwiftUI
struct ItemDetail: View { let id: Int; var body: some View { Text("Item #\(id)") } }
struct DeepLinkBasicDemo: View {
@State private var path: [Int] = []
var body: some View {
NavigationStack(path: $path) {
Text("Home")
.onOpenURL { url in
if url.scheme == "myapp", url.host == "item", let id = Int(url.lastPathComponent) {
path.append(id)
}
}
.navigationDestination(for: Int.self) { id in ItemDetail(id: id) }
.navigationTitle("Deep Links")
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View { DeepLinkBasicDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}
In the example above, the onOpenURL modifier is used to handle incoming URLs.
Route mapping
Handle multiple hosts and route to different destinations.
Example
import SwiftUI
struct ProfileView: View { let user: String; var body: some View { Text("Profile: \(user)") } }
struct ArticleView: View { let slug: String; var body: some View { Text("Article: \(slug)") } }
enum Route: Hashable { case item(Int), profile(String), article(String) }
struct DeepLinkRoutesDemo: View {
@State private var path: [Route] = []
var body: some View {
NavigationStack(path: $path) {
Text("Home")
.onOpenURL { url in
guard url.scheme == "myapp" else { return }
switch url.host {
case "item": if let id = Int(url.lastPathComponent) { path.append(.item(id)) }
case "profile": path.append(.profile(url.lastPathComponent))
case "article": path.append(.article(url.lastPathComponent))
default: break
}
}
.navigationDestination(for: Route.self) { route in
switch route {
case .item(let id): Text("Item #\(id)")
case .profile(let u): ProfileView(user: u)
case .article(let s): ArticleView(slug: s)
}
}
.navigationTitle("Routes")
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View { DeepLinkRoutesDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}
In the example above, the onOpenURL modifier is used to handle incoming URLs.