< How to use programmatic navigation in SwiftUI | How to create a two-column or three-column layout with NavigationSplitView > |
Updated for Xcode 14.2
New in iOS 16
When managing SwiftUI’s NavigationStack
path using a NavigationPath
object, we can save and load our whole path using Codable
– we can store the complete navigation stack and restore it later, so the user comes back to the app exactly where they left it.
This is best handled by wrapping up your storage in a separate ObservableObject
class, which can take the responsibility of loading and saving path data away from your views. For example, this class loads a saved when it’s created, and saves the path whenever its NavigationPath
property gets changed:
class PathStore: ObservableObject {
@Published var path = NavigationPath() {
didSet {
save()
}
}
private let savePath = URL.documentsDirectory.appending(path: "SavedPathStore")
init() {
if let data = try? Data(contentsOf: savePath) {
if let decoded = try? JSONDecoder().decode(NavigationPath.CodableRepresentation.self, from: data) {
path = NavigationPath(decoded)
return
}
}
}
func save() {
guard let representation = path.codable else { return }
do {
let data = try JSONEncoder().encode(representation)
try data.write(to: savePath)
} catch {
print("Failed to save navigation data")
}
}
}
That’s a neatly reusable class that you can put to work immediately – as long as the data you write into NavigationPath
conforms to Codable
, it will work.
For example, we could create a simple detail view capable of showing a number the user selected while also allowing them to navigate deeper by selecting another number, then use that with our PathStore
class so that navigation is automatically loaded and saved:
struct DetailView: View {
var id: Int
var body: some View {
VStack {
Text("View \(id)")
.font(.largeTitle)
NavigationLink("Jump to random", value: Int.random(in: 1...100))
}
}
}
struct ContentView: View {
@StateObject private var pathStore = PathStore()
var body: some View {
NavigationStack(path: $pathStore.path) {
DetailView(id: 0)
.navigationDestination(for: Int.self, destination: DetailView.init)
.navigationTitle("Navigation")
}
}
}
If you run that code, you’ll see you can navigate through as many levels of DetailView
as you want, and your data will automatically be stored – you can quit the app and return just fine, and your navigation history will remain intact.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Link copied to your pasteboard.