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

Demo.swift

ContentView.swift

App.swift

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")
}
} }

In the example above, the onOpenURL modifier is used to handle incoming URLs.



Route mapping

Handle multiple hosts and route to different destinations.

Example

Demo.swift

ContentView.swift

App.swift

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")
}
} }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *