In a SwiftUI e-commerce app, how do you turn a link to an order's shipment screen, three levels deep, into a NavigationStack with a working Back path?
answer
- the link becomes data, not views
- onOpenURL hands over a URL
- router parses into route values
- assign the whole path at once
basics
~20 sReceive the link with onOpenURL, let a router parse the URL into route values, and assign the whole bound path in one step, such as [.orders, .order(id:), .shipment(orderID:)]. The stack shows the shipment and Back walks the earlier screens.
solid answer
~40 sI keep navigation in a main-actor `@Observable` router that owns the stack's path, say `[Route]`, and bind it with `NavigationStack(path: $router.path)`. `onOpenURL(perform:)` on the view hosting the stack receives the link; SwiftUI hands a universal link over directly as a `URL`. The router parses the path components into route values that carry identifiers, not models, and assigns the whole array in one go: `[.orders, .order(id: "A1"), .shipment(orderID: "A1")]`. SwiftUI then shows the last screen, and Back reveals the order and then the orders list, because each one is a real entry in the path. I register `navigationDestination(for: Route.self)` at the stack's root so every route resolves, ignore links I can't parse, and route notification taps, which don't arrive through `onOpenURL`, into the same router method.
code
swift · 22 linesenum Route: Hashable, Codable {
case orders
case order(id: String)
case shipment(orderID: String)
}
@Observable @MainActor
final class Router {
var path: [Route] = []
// https://shop.example.com/orders/A1/shipment -> three screens deep
func open(_ url: URL) {
let parts = url.pathComponents.filter { $0 != "/" }
guard parts.first == "orders" else { return } // unknown link: keep the stack
var newPath: [Route] = [.orders]
if parts.count >= 2 { newPath.append(.order(id: parts[1])) }
if parts.count == 3, parts[2] == "shipment" {
newPath.append(.shipment(orderID: parts[1]))
}
path = newPath // one assignment: the last screen shows, Back walks the rest
}
}go deeper
Recall that onOpenURL receives a link as a URL and that a NavigationStack shows whatever screens its bound path lists.
Explain how parsing the URL into route values and assigning the path builds every intermediate screen, so Back behaves as if the user had tapped through.
Show the production edge cases: invalid IDs, links that arrive mid-navigation, notification taps through a different API, tabs and sheets, and a restore racing the link.
Argue for a single routing entry point that every source of navigation calls, and for route types that keep links testable without UI.
## The goal A shopper taps a link, such as `https://shop.example.com/orders/A1/shipment`, and the app should open on the **shipment tracking** screen for order A1. Back should go to the order, then to the orders list, then to the home screen: a real stack, not a lone screen with no way out. In SwiftUI this is a data problem. A `NavigationStack` bound to a path shows exactly the screens its path describes, so a deep link is solved by **computing the right path and assigning it**. ## The pieces - **A route type.** A `Hashable` (and, for restoration, `Codable`) enum with one case per pushable screen: `.orders`, `.order(id:)`, `.shipment(orderID:)`. Cases carry identifiers; Apple's navigation-stack guide advises keeping path elements lightweight rather than using model types. - **A router.** An `@Observable` class, isolated to the main actor, that owns `var path: [Route]`. The view that hosts the stack keeps it in `@State` and binds `$router.path`. Child screens can reach it through the environment. - **One destination at the root.** `navigationDestination(for: Route.self)` on the stack's root view, switching over every case. Registering every route type at the root means a path built in one assignment never depends on a destination that only a pushed screen declares. - **An entry point.** `onOpenURL(perform:)` (iOS 14 and later) registers a handler that SwiftUI calls when the app receives a universal link or a custom-scheme URL. Apple's documentation notes that SwiftUI passes a universal link directly as a `URL`, while other user activities such as Handoff arrive through `onContinueUserActivity(_:perform:)`. ## Building the stack The router turns the URL into routes and assigns them **in one statement**: 1. Split the URL's path components, dropping the `/` separator. 2. Validate the first segment; an unknown link returns early and leaves the current stack alone. 3. Build `[.orders]`, then add `.order(id:)` if an ID follows, then `.shipment(orderID:)` if the next segment is `shipment`. 4. Assign the array to `path`. Apple's `NavigationStack` documentation describes exactly this behaviour: setting the path to two values shows the detail for the last one, and navigating back removes it and reveals the one before. The Back chain is not faked; each screen is a real entry, so Back, swipe gestures and `@Environment(\.dismiss)` all work as they would after three taps. ## Edge cases a senior answer covers - **Existing navigation.** Assigning the path replaces whatever the user had open. Whether a link should replace, or which back stack it should build at all, is a product decision covered in the mobile system design material on navigation and entry points; the SwiftUI mechanism is one assignment either way. - **Invalid or stale identifiers.** The router can't know whether order A1 still exists. The destination screen loads by ID and shows a not-found state; the router never needs the model. - **Notification taps.** A tapped notification is delivered to the UserNotifications framework's delegate, not to `onOpenURL`. Extract the URL or order ID from its payload and call the same `router.open(_:)`, so every entry point builds stacks one way. - **Tabs and presented sheets.** If the stack lives inside one tab, the router also selects that tab, and a sheet already on screen should be dismissed first; both belong to the lessons on tabs and on modal presentation. - **Which scene receives the link.** On iPad with several windows, SwiftUI picks the scene for an incoming URL; Apple points to `handlesExternalEvents(matching:)` for influencing that choice. - **Restoration racing a link.** If the app also restores a saved path on launch, let the link win: restore only into an empty path. | Concern | SwiftUI mechanism | |---|---| | receive the link | `onOpenURL(perform:)` on a view in the scene | | describe screens | `Hashable` route enum with IDs | | build the stack | assign the bound `[Route]` in one statement | | resolve screens | one `navigationDestination(for: Route.self)` at the root | | leave a screen | Back, swipe or `dismiss`, all of which edit the path | ## Why a typed array here A single `Route` enum lets the router read the path, so it can, for example, skip re-pushing the order if it is already on top. A `NavigationPath` would work for building the stack, but it can't be inspected, and type-erased values make the parser harder to test. Because `open(_:)` is a plain method that produces an `Equatable` array, it can be unit-tested without any UI.
- A tap on a shipping-update notification should open the same SwiftUI screen; does onOpenURL fire for it?No. `onOpenURL` receives universal links and custom-scheme URLs. A notification response is delivered to the UserNotifications framework's delegate, so read the order ID or URL from the payload there and call the same `router.open(_:)`. Keeping one parsing method means links and notifications always build the same stack.
- Why register navigationDestination(for: Route.self) on the root view rather than on the screen each route is pushed from?A destination declared on a pushed screen exists only once that screen is in the hierarchy. A deep link assigns all three routes at once, so the safest design is one destination at the stack's root that resolves every case. It also keeps the route-to-screen mapping in one place that is easy to review.
- How do you test the link handling without UI tests?`open(_:)` is a plain main-actor method that produces a `[Route]`, and `Route` is `Hashable`, so equality comes for free. A unit test creates a `Router`, calls `open` with sample URLs, valid, unknown and truncated, and compares `router.path` with the expected array. The lesson on unit and snapshot checks covers the test setup.
- Push each screen with a delay so the animations finish
- Put the Order model itself into the route enum
- Show the shipment screen alone; Back is not needed after a link
- Declare each route's destination only on the screen that pushes it
- Notification taps arrive through onOpenURL like any link