The problem
NavigationLink(destination:) is fine until something outside the user’s finger needs to move the stack. A push notification wants to open a book’s reviews. A universal link points at an author page. The app relaunches and should land where the user left off. None of that works when the views on the stack are the only record of where you are. You need the navigation state as data, in one place, that code can read, replace and save.
NavigationStack (iOS 16+) gives you that through its path parameter. The rest of this page builds a small router around it, then adds deep links, restoration, tabs and split views.
Step 1: routes as small values
Start with an enum that describes every screen you can push. Apple’s navigation stack guide is direct about what goes in it: keep path elements lightweight and don’t use them to carry model data. Store identifiers. A pushed screen looks its data up when it appears, so a restored path never shows a stale copy of a model.
import Foundation
enum Route: Hashable, Codable, Sendable {
case book(UUID)
case reviews(bookID: UUID)
case author(UUID)
}
Conforming to Codable costs nothing now and is what makes restoration possible later.
You have two choices of path type. A [Route] array is homogeneous, fully typed and encodes with plain JSONEncoder. NavigationPath is type-erased and can hold values of different types, which helps when separate feature modules each define their own route type. Apple’s NavigationPath docs show both. Prefer the array while one enum can describe your app. You get exhaustive switch statements, and you can inspect and rewrite the path with ordinary collection code.
Step 2: a router that owns the path
import SwiftUI
@MainActor
@Observable
final class Router {
var path: [Route] = []
func push(_ route: Route) {
path.append(route)
}
func popToRoot() {
path.removeAll()
}
@discardableResult
func open(_ url: URL) -> Bool {
guard let routes = DeepLink.routes(for: url) else { return false }
path = routes
return true
}
}
The router lives in the root view of each scene, not in the App struct. Majid Jabrayilov makes this point in his deep linking article: a path stored at the app level would be shared across every window on iPad and Mac, so opening a second window would mirror the first. App-wide data such as your database or account state still belongs at the app level. Navigation is per scene.
struct RootView: View {
@State private var router = Router()
var body: some View {
NavigationStack(path: $router.path) {
BookListView()
.navigationDestination(for: Route.self) { route in
switch route {
case .book(let id): BookScreen(bookID: id)
case .reviews(let id): ReviewsScreen(bookID: id)
case .author(let id): AuthorScreen(authorID: id)
}
}
}
.environment(router)
.onOpenURL { url in
router.open(url)
}
}
}
Views deeper in the stack read the router with @Environment(Router.self) and call push or popToRoot. Rows can keep using NavigationLink(value:), because a value link appends to the same bound path.
Attach navigationDestination(for:) to the stack’s root content, outside any List or LazyVStack. Apple’s documentation warns that lazy containers create children only when they scroll on screen, so a destination declared inside a row may not exist when the stack needs it.
Step 3: parse deep links into a whole path
onOpenURL(perform:) (iOS 14+) receives both custom scheme URLs and universal links. Apple’s documentation notes that SwiftUI hands universal links to this modifier as a plain URL, so you don’t need to dig through an NSUserActivity. Handoff and other activities still arrive through onContinueUserActivity(_:perform:).
Keep parsing in a pure function that knows nothing about SwiftUI. It is easier to reason about, and you can reuse it from a notification handler or an App Intent.
import Foundation
enum DeepLink {
static func routes(for url: URL) -> [Route]? {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
return nil
}
var parts = components.path.split(separator: "/").map(String.init)
if components.scheme == "bookshelf", let host = components.host {
parts.insert(host, at: 0)
}
guard parts.count >= 2, let id = UUID(uuidString: parts[1]) else { return nil }
switch parts[0] {
case "books":
var routes: [Route] = [.book(id)]
if parts.count >= 3, parts[2] == "reviews" {
routes.append(.reviews(bookID: id))
}
return routes
case "authors":
return [.author(id)]
default:
return nil
}
}
}
bookshelf://books/<id>/reviews and https://<your domain>/books/<id>/reviews both produce [.book(id), .reviews(bookID: id)]. The user lands on the reviews screen with the book underneath it, so the back button goes somewhere sensible.
Assign the whole array in one step. Building the path with repeated append calls from the current state leaves you with whatever the user had already pushed, plus the link. Replacing it is the same as popping to root and pushing parent to child, without the intermediate frames.
Return false for URLs you don’t recognize and decide what the app does with them. Silently ignoring a link a user tapped looks broken. Showing a short message or falling back to the root screen is better.
Deep links often need a gate in front of them. If the user is signed out, store the pending routes, show the sign-in flow, and apply them when the session becomes available.
Step 4: save and restore the path
SceneStorage (iOS 14+) persists small values per scene and restores them when the system recreates that scene. Apple’s docs set the limits: keep the data lightweight, expect no guarantee about when it is written, and don’t store anything sensitive. A list of route identifiers fits all three.
import SwiftUI
import os
struct RestoringRootView: View {
@State private var router = Router()
@SceneStorage("navigation.path") private var savedPath = Data()
private let log = Logger(subsystem: "Bookshelf", category: "Navigation")
var body: some View {
NavigationStack(path: $router.path) {
BookListView()
.navigationDestination(for: Route.self) { route in
RouteView(route: route)
}
}
.environment(router)
.onOpenURL { url in router.open(url) }
.task { restore() }
.onChange(of: router.path) { save() }
}
private func restore() {
guard router.path.isEmpty, !savedPath.isEmpty else { return }
do {
router.path = try JSONDecoder().decode([Route].self, from: savedPath)
} catch {
log.error("Discarded saved navigation path: \(error.localizedDescription)")
savedPath = Data()
}
}
private func save() {
do {
savedPath = try JSONEncoder().encode(router.path)
} catch {
log.error("Could not encode navigation path: \(error.localizedDescription)")
}
}
}
RouteView is the same switch from Step 2, pulled into its own view. The guard router.path.isEmpty line settles a race on cold launch: if a deep link already set the path, the link wins over the saved state.
If you use NavigationPath, encode path.codable and decode a NavigationPath.CodableRepresentation. Paul Hudson points out in How to save NavigationStack paths using Codable that NavigationPath only requires Hashable, so the compiler can’t tell you a pushed value isn’t Codable. In that case codable returns nil and the save quietly does nothing. A [Route] array turns that into a compile error, which is one more reason to prefer it.
Restored routes can point at data that no longer exists. A book deleted on another device, or an enum case you removed in an update, will fail to resolve or fail to decode. Handle both: decoding errors reset the stored path, and each destination screen shows an empty state with a way back when its identifier finds nothing.
Step 5: tabs get one path each
A TabView with a single shared path makes every tab jump when one of them navigates. Give each tab its own array and have the router decide which tab a link opens in.
import SwiftUI
enum AppTab: Hashable {
case library, authors
}
@MainActor
@Observable
final class TabRouter {
var selectedTab: AppTab = .library
var libraryPath: [Route] = []
var authorsPath: [Route] = []
func open(_ url: URL) {
guard let routes = DeepLink.routes(for: url), let first = routes.first else { return }
switch first {
case .author:
selectedTab = .authors
authorsPath = routes
case .book, .reviews:
selectedTab = .library
libraryPath = routes
}
}
}
Thomas Ricouard’s open source AppRouter package follows the same shape at larger scale: a router tracks the selected tab, keeps an independent stack per tab, manages one presented sheet, and maps URLs to destinations. It targets iOS 17, which matches the APIs used here. Reading its source is a quick way to see how far the pattern stretches before you need anything more elaborate.
Sheets belong in the router too when a deep link can open one. Model the presented sheet as an optional Identifiable enum on the router and bind it with .sheet(item:).
Step 6: NavigationSplitView and the detail stack
On iPad and Mac, NavigationSplitView (iOS 16+) drives navigation from the sidebar’s List selection. You can embed a NavigationStack in the detail column. Apple’s docs describe the interplay: a link activated in an earlier column replaces what the detail stack shows over its root, and a link in the same column pushes onto it. On iPhone the split view collapses into a single stack.
That gives you two pieces of state: the selection and the detail path. Keep both in one router, and clear the path when the user picks a new item.
import SwiftUI
@MainActor
@Observable
final class SplitRouter {
var selection: UUID?
var detailPath: [Route] = []
func select(_ id: UUID?) {
selection = id
detailPath = []
}
func open(bookID: UUID, then routes: [Route]) {
selection = bookID
detailPath = routes
}
}
struct LibrarySplitView: View {
let books: [Book]
@State private var router = SplitRouter()
var body: some View {
NavigationSplitView {
List(books, selection: Binding(
get: { router.selection },
set: { router.select($0) }
)) { book in
Text(book.title)
}
} detail: {
NavigationStack(path: $router.detailPath) {
Group {
if let id = router.selection {
BookScreen(bookID: id)
} else {
ContentUnavailableView("Select a book", systemImage: "book")
}
}
.navigationDestination(for: Route.self) { route in
RouteView(route: route)
}
}
}
}
}
struct Book: Identifiable, Hashable {
let id: UUID
var title: String
}
The custom binding matters. A tempting alternative is .onChange(of: router.selection) { router.detailPath = [] }, and it breaks deep links: open(bookID:then:) sets the selection and the path together, then onChange runs after the update and wipes the path you just set. Putting the reset in the user’s selection path keeps programmatic navigation intact.
ContentUnavailableView requires iOS 17. BookScreen, ReviewsScreen, AuthorScreen and BookListView stand for your own screens.
Traps
- View-destination links can’t be restored.
NavigationLink(destination:label:)pushes a view without touching your path. Apple’s guide notes that your app gets no hook for it and that its state can’t be restored programmatically. Mixing it into a router-driven stack means some screens never show up inpath. If you push a value while one of these is on top, SwiftUI pops the view destinations first. - One destination per type. Declare
navigationDestination(for: Route.self)once per stack, on the root content. Scattering destinations across feature screens makes it hard to tell which screens a restored path can reach. - Heavy values in the path. Passing a full model as a route ties the screen to a snapshot. Identifiers keep the stack small,
Codableand current. - Handlers on transient views. Put
onOpenURLon the root view that is present for the whole life of the scene. A handler on a screen deep in the stack only exists while that screen does. - Saving secrets.
SceneStorageis not encrypted storage. Routes with tokens or personal data don’t go there.
Decision table
| Situation | Use |
|---|---|
| One stack, one route enum | NavigationStack(path:) with [Route] in an @Observable router |
| Feature modules define their own route types | NavigationPath, check codable before saving |
| Optional single destination, such as a selected item | navigationDestination(item:) (iOS 17+) |
| Push driven by a Boolean | navigationDestination(isPresented:) |
| Tabs | One path per tab, router owns selected tab |
| iPad sidebar plus detail | NavigationSplitView, selection and detail path in one router |
| Restore after relaunch | Encode the path into @SceneStorage, deep links take priority |
Sources and further reading
- Understanding the navigation stack Apple Developer Documentation
- NavigationPath Apple Developer Documentation
- NavigationSplitView Apple Developer Documentation
- onOpenURL(perform:) Apple Developer Documentation
- SceneStorage Apple Developer Documentation
- Mastering NavigationStack in SwiftUI. Deep Linking. Majid Jabrayilov, Swift with Majid
- How to save NavigationStack paths using Codable Paul Hudson, Hacking with Swift
- AppRouter Thomas Ricouard