Join our newsletter! Get Swift & SwiftUI tips, project updates, and discounts on our books...JOIN OUR NEWSLETTER!Monthly Swift insights, updates, and deals...
Quick Tip Icon
Quick Tip

Testing SceneStorage state persistence in Xcode

When we need to ensure that an iOS app preserves its state, such as tab selection or navigation, across launches, we can use the SceneStorage property wrapper in SwiftUI. This allows us to retain small pieces of UI-related state automatically.

struct ContentView: View {
    @SceneStorage("selectedTab")
    private var selectedTab: Int = 0
    
    var body: some View {
        TabView(selection: $selectedTab) {
            ...
        }
    }
}

We can test whether state preservation works as expected using the Xcode simulator, but it's crucial to follow the correct sequence of steps. Otherwise, the state might not be restored, leading us to mistakenly think that our implementation is incorrect.

To properly test state preservation with SceneStorage in Xcode:

  1. Run the app in the Xcode simulator.
  2. Change the state (e.g., switch tabs or navigate within the app).
  3. Press the Home button in the simulator to send the app to the background.
  4. Press the Stop button in Xcode to terminate the app.
  5. Run the app again in Xcode and check if the state is preserved.

SwiftUI automatically clears SceneStorage values if the user explicitly quits the app from the app switcher. So when testing state preservation, avoid force-quitting the app and follow the steps above instead.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Level up your Swift skills!$35

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms

Level up your Swift skills!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35