NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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.

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

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: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.