NEW BOOK! SwiftUI Fundamentals: The essential guide to SwiftUI core concepts and APIs. Learn more ...NEW BOOK! SwiftUI Fundamentals:Master SwiftUI core concepts and APIs. Learn more...
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.

SwiftUI Fundamentals by Natalia Panferova book coverSwiftUI Fundamentals by Natalia Panferova book cover

Deepen your understanding of SwiftUI!$35

The essential guide to SwiftUI core concepts and APIs

SwiftUI Fundamentalsby Natalia Panferova

  • Explore the key APIs and design patterns that form the foundation of SwiftUI
  • Develop a deep, practical understanding of how SwiftUI works under the hood
  • Learn from a former Apple engineer who worked on widely used SwiftUI APIs

Deepen your understanding of SwiftUI!

The essential guide to SwiftUI core concepts and APIs

SwiftUI Fundamentals by Natalia Panferova book coverSwiftUI Fundamentals by Natalia Panferova book cover

SwiftUI Fundamentals

by Natalia Panferova

$35