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 few techniques that allow for launching the app with an instruction to display specific app page instead of the default landing screen:
- Deep linking with Universal Links or Custom URL Scheme
- Local and Remote Notifications
- Siri Shortcuts
- Spotlight Search
- Home Screen Quick Actions
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:
func scene(_ scene: UIScene, continue userActivity: NSUserActivity)func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>)
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:
- Variable defined on an external
ObservableObject(with or without
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
When we type
$ before the variable name with the attribute
@EnvironmentObject, we retrieve a special entity of type
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
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
.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
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
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:
.. 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
So far so good. But once you try another
The code works just the same way, but the
List doesn't push the
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
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
The sample project that supports deep links can be found on Github:
A demo project showcasing the setup of the SwiftUI app with Clean Architecture. The app uses the restcountries.eu REST…
It was initially created for illustration of the article Clean Architecture for SwiftUI, I recommend you to check it out as well:
Clean Architecture for SwiftUI
Are VIPER, MVVM, Clean Swift (VIP), RIBs or ELM suitable for a SwiftUI project?
Follow me on Twitter to stay tuned about the coming posts!
All my articles are available without the paywall in my tech blog (RSS link):