Home > AI > IOS > SwiftUI >

@SceneStorage

It is used to store small amounts of data within the scope of individual app scene instances and is ideal for saving and restoring the state of a screen between app launches. 

Consider a situation where a user, partway through entering information into a form within an app, is interrupted by a phone call or text message, and places the app into the background. The user subsequently forgets to return to the app, complete the form and save the entered information. If the background app were to exit (either because of a device restart, the user terminating the app, or the system killing the app to free up resources) the partial information entered into the form would be lost. Situations such as this can be avoided, however, by using scene storage to retain and restore the data.
Example:

struct ContentView: View {
    // will save if App relaunch
    @SceneStorage("city") var city: String = "Shanghai"
    
    // will lost if App relaunch
//    @State var city: String = "Shanghai"
    
    // the variable has to conform ObservableObject
//    @StateObject var city: String = "Shanghai"

    var body: some View {
        TextEditor(text: $city)
            .padding()
    }
}

Leave a Reply