The provided content discusses programmatic deep link navigation in SwiftUI, detailing methods for navigating to specific content screens in response to deep link instructions.
Abstract
The article delves into the intricacies of implementing deep link navigation within SwiftUI applications. It explains the importance of integrating apps seamlessly into the iOS system, including techniques such as deep linking, notifications, quick actions, and Siri Shortcuts. The author highlights the challenge of navigating to a specific app page programmatically, which is crucial for a compelling user experience. The article explores the transition from UIKit to SwiftUI, emphasizing the new paradigms for UI construction and navigation. It presents two main approaches for achieving programmatic navigation: centralizing app state using AppState and .environmentObject(...), or broadcasting navigation parameters through a Combine Publisher. The author also addresses a pitfall with programmatic navigation through List views, where the target item must be visible for the navigation to work, and suggests workarounds for this limitation.
Opinions
The author suggests that while there are many ways to achieve deep link navigation in UIKit, many of them are not elegant, implying that SwiftUI offers a more streamlined approach.
The author posits that the use of Binding in SwiftUI is key to programmatic navigation, as it allows for direct read and write access to the state without transferring ownership.
There is an opinion that using a centralized AppState is preferable for maintaining navigation parameters, as it acts as a single source of truth and does not require manual resetting of values.
The author indicates a preference for the centralized AppState approach over using a Publisher, due to its reliability in ensuring that navigation parameters remain selected even if the content view is not yet ready to display them.
The author expresses frustration with a specific issue related to List in SwiftUI, where programmatic navigation does not work for items not currently visible, calling it a "hidden pitfall" and providing a critique of the current API limitations.
A suggestion is made that developers might consider not relying on programmatic navigation through List due to its limitations, implying that the current SwiftUI API for List may need improvements to support more robust navigation scenarios.
Programmatic Deep Link Navigation in SwiftUI
Deep links, notifications, quick actions, shortcuts, and more
In this highly competitive market, developers do their best to achieve a compelling user experience in their mobile apps. This includes not only building amazing features available inside their apps, but also a native integration into the iOS system.
Among these integrations there are a few techniques that allow for launching the app with an instruction to display a specific app page instead of the default landing screen:
While you could easily find a tutorial for either of these features, there is one topic I found unconsidered yet:
Following the deep link instruction, how can we programmatically navigate to a custom content screen in a SwiftUI app?
These were many ways to achieve this in UIKit (most of which were ugly), but SwiftUI brought in a completely new paradigm for building the UI with its own way for the screen navigation.
A functional successor of AppDelegate in SwiftUI apps is SceneDelegate, which inherited these two methods for providing the app with the navigation instructions:
The challenge here is to forward this instruction to the SwiftUI’s view hierarchy for displaying the right content.
All we have by default is the ContentView created in the scene(_:, willConnectTo:, options:), without a way to access the underlying views.
The only way we can toggle what’s displayed is by changing the state bound to the views.
There are two different types of state to which the View can be bound:
Local @State variable
Variable defined on an external ObservableObject (with or without @Published attribute)
Let’s take a TabView (a replacement for UITabBarController) as the experiment subject and build a simple app that looks like this:
The view-state binding for toggling the tabs can be built using @State:
…and using ObservableObject:
When we type $ before the variable name with the attribute @State, @ObservedObject or @EnvironmentObject, we retrieve a special entity of type Binding.
Binding is the access token you can pass around for providing direct read and write access to the value without granting ownership (in terms of retaining a reference type) or copying (for a value type).
When the user selects a tab in the TabView, it unilaterally changes the value through Binding and assigns the associated .tag(...) to the selectedTab variable. This works the same way for both @State and ObservableObject
The programmer can also assign a value to that selectedTab variable at any time – and the TabView will toggle the displayed tab immediately.
This is the key to the programmatic navigation in SwiftUI.
Every view that toggles the displayed hierarchy, be that TabView, NavigationView or .sheet(), now uses Binding to control what's displayed.
So if we had access to the Binding (or factual underlying state) in the SceneDelegate, we would be able to tell the SwiftUI views to display the screen we want instead of the default one.
There are two approaches to this problem.
1. Storing the navigation variables in the centralized AppState
The first approach implies creating a shared app state that is injected in the view hierarchy though .environmentObject(...) method on the root view:
2. Broadcasting navigation parameters through external Publisher
The second approach is to use a Publisher from Combine to deliver the navigation state updates:
This is really up to you which method to use, but there are conceptual differences.
The first approach assures that the selected navigation parameters remain selected even if the content view cannot pick it up yet. Some view along the way may be showing a loading indicator, but once it finishes and presents the final child view hierarchy, one of the children can eventually pick up the navigation parameter and behave accordingly.
This simply won’t work with the second approach, unless you change PassthroughSubject to CurrentValueSubject to always hold the navigation state. But in this case, you'd need to reset the value manually once the navigation is complete.
You don’t need to reset the navigation state for the first approach, because App State, holing the navigation parameters, is the single source of truth for the entire program and SwiftUI will be updating those values as the user continues navigating in the app.
Navigation through multiple views
Using one of the approaches described above you can programmatically navigate to a screen at any depth.
The only requirement: for every “navigatable” view along the way to the deep link’s target view, you need to allocate a separate navigation parameter in the AppState or in the broadcasted message.
Then, inside the scene(_ scene, openURLContexts:) you need to toggle all the navigation parameters at once, and the SwiftUI view hierarchy will transition to the target screen at one step.
List doesn't correctly support programmatic navigation
While I was implementing deep links in the sample project, I found a hidden pitfall with programmatic navigation through List
Consider this simple setup:
The app simply shows a list of 100 text items. Let’s suppose, we implemented a deep link that opens ItemDetailsView for item with specified id. We try it with the URL like so:
https://www.100items.com/details?id=5
.. and it works. The app launches and parses the URL to assign 5 to the appState.selectedItemId and immediately shows ItemDetailsViewpushed on top of the List.
So far so good. But once you try another id, say 75:
https://www.100items.com/details?id=75
The code works just the same way, but the Listdoesn't push the ItemDetailsView.
What is going on? We know the item with id 75 exists in the list, but for some reason, the details screen is not get pushed.
It turns out that the List’s item we’re pushing to has to be currently visible in the List in order for the programmatic navigation to work.
Once you scroll the list to make the target item visible, you’ll see an unappealing effect: the scrolling suddenly stops and details view appears without animation on the navigation stack:
List is optimized the same way UITableView was, so it tracks the displayed items and lazily loads the content as needed.
Because of this, the List is unaware of the Item with id=75 and so it does nothing until it gets to know it is actually in the array.
This bug could be fixed if we had access to the scroll offset of the List to adjust it for this edge case, but we cannot: there is no API to change the offset of the List.
A hotfix to this issue I see right now is moving the target item to the first position in the array so the List could pick up the NavigationLink correctly. Or we could simply not rely on programmatic navigation through the List
The sample project that supports deep links can be found on Github: