WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

How to save and load NavigationStack paths using Codable

Paul Hudson    @twostraws   

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% in my WWDC23 sale.

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.

Save 50% on all our books and bundles!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.2/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.