NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

What is the @SceneStorage property wrapper?

Paul Hudson    @twostraws   

Updated for Xcode 12.5

New in iOS 14

If you want to save unique data for each of your screens, you should use SwiftUI’s @SceneStorage property wrapper. This works a bit like @AppStorage in that you provide it with a name to save things plus a default value, but rather than working with UserDefaults it instead gets used for state restoration – and it even works great with the kinds of complex multi-scene set ups we see so often in iPadOS.

For example, if you have a text editor and want to store what the user was typing, you should use this kind of code:

struct ContentView: View {
    @SceneStorage("text") var text = ""

    var body: some View {
        NavigationView {
            TextEditor(text: $text)
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}

Note: I’ve used StackNavigationViewStyle there because it forces the iPad to allocate all the space to our text editor.

Because that uses @SceneStorage, SwiftUI will automatically make sure that each scene instance has its own copy of the text – if you run the app side by side both will save and restore their data correctly.

Now, before you use @SceneStorage there are some important warnings from Apple:

  • Don’t save lots of data; save just what you need for state restoration.
  • Never store sensitive data in scene storage, because it isn’t secure.
  • If the user goes to the app switcher and destroys your app, the scene storage is also destroyed.
Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started now

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

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.