Restoring navigation after the system kills the app

Platform & distribution Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

A SwiftUI app should reopen on the same detail screen after the system kills it. Best approach?

Options
Hint 1 of 1

What is the smallest thing that describes where the user was?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Store the route path, such as ids, in @SceneStorage and rebuild the NavigationStack path from it

Correct. It's small, per scene, and restored automatically.

Why not the others?
  • B Save the whole view model in UserDefaults. It's heavy, and goes stale.
  • C Keep the app alive in the background. You can't prevent the system from ending it.
  • D Use @State. @State is lost when the process ends.

30-second answer

Save a small, codable description of where the user was, not the views themselves. In SwiftUI, store a route path (for example NavigationPath's codable representation or an array of route enums) in @SceneStorage. In UIKit, return an NSUserActivity from stateRestorationActivity(for:) and rebuild the stack from it on connection. Re-fetch data by id and handle items that no longer exist.

Practise saying it · 45 s. No recording, just a timer

Explain state restoration.

Say your answer out loud, then check which of these points you covered:

  • Save routes, not views
  • @SceneStorage / NSUserActivity
  • Rehydrate by id

Deep dive

@SceneStorage is per scene, so each window restores separately.

Store ids, not whole models.

Test by killing the app from Xcode while in the background, not by swiping it away.

Swiping the app away in the app switcher discards saved scene state by design.

Common mistakes

  • Storing whole view models.
  • Crashing when a restored id no longer exists.

Senior take & follow-ups

Seniors restore from ids and handle missing data gracefully.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why does swiping away not restore?

    Show hint

    The user explicitly closed it.

  2. How do you test restoration?

    Show hint

    Background the app and stop it from Xcode.

Suggest a fix if something here is wrong or out of date.