State Restoration in SwiftUI | Kodeco, the brand new


Discover ways to use SceneStorage in SwiftUI to revive iOS app state.

In nearly any app conceivable, some state shall be outlined by actions the person has taken — the tab the person final chosen, the objects the person added to a basket or the contents of a draft message.

It could be complicated for customers in the event that they had been to cease utilizing your app for a short time, then come again to seek out the state misplaced. However that is the default habits for iOS apps. Why? As a result of after a person places an app into the background, the working system might select to terminate it at any time. When this occurs, the system discards in-memory state.

There’s a characteristic in iOS the place the working system can restore state when an app is re-launched. This is called state restoration.

On this tutorial, you’ll study:

  • The right way to add state restoration to your SwiftUI apps.
  • The @SceneStorage property wrapper for saving state of easy information.
  • Utilizing NSUserActivity to move state when launching an app.

Time to get began!

Getting Began

Obtain the undertaking supplies by clicking the Obtain Supplies button on the high or backside of this tutorial. The supplies comprise a undertaking known as Hawk Notes. This tutorial builds an app for making examine notes for the Shadow Skye sequence, a trilogy of epic fantasy books.

The demo app - Hawk Notes

Open the starter undertaking. Now, construct and run the app utilizing Product ▸ Run from the toolbar or by clicking the Run arrow on the high of the Venture Navigator. As soon as working, the app shows 4 tabs: one for every of the three books and a fourth on your favourite characters.

Inside every of the primary three tabs, you may see 4 issues:

  • An summary of the e book.
  • A hyperlink to view it on Amazon.
  • An inventory of examine notes you can also make in regards to the e book, which is presently empty.
  • An inventory of the e book’s essential characters.

Faucet a personality, and the app navigates to a character element display. This display incorporates a synopsis for the character in addition to a listing of notes you may add about that character. It’s also possible to faucet the center to mark this character as considered one of your favorites.

Lastly, faucet the Favorites tab. There, the app lists all of the characters, break up into two sections: one on your favorites and one other for all of the others.

Swap again to Xcode and have a look across the code. Open ContentView.swift. That is the entry level into the app correct. Discover the way it defines a BookModel setting object. This mannequin incorporates the knowledge for every e book and is the first information supply for the app. The content material view itself shows a tab view with the 4 tabs from above — one for every e book plus the favorites tab.

Subsequent, open BookView.swift. That is the view for displaying a e book. The view contains a vertical stack containing an summary, a hyperlink to view the e book on Amazon, a listing of notes and eventually, a listing of characters for this e book.

Subsequent, open CharacterView.swift. Right here, a ScrollView incorporates a VStack displaying views for the character’s avatar, a toggle change for marking the character as a favourite, a synopsis for the character and eventually, the notes for the character.

Lastly, open FavoritesView.swift. This view reveals a listing of all the primary characters for the three books break up into two sections: first, a listing of your favourite characters, and secondly, a listing of all the opposite characters.

Swap to the Simulator and choose the third tab for The Burning Swift. Now, put the app within the background by deciding on Gadget ▸ Dwelling. Subsequent, change again to Xcode and cease the app from working by deciding on Product ▸ Cease within the menu. Construct and run the app once more.

Notice: You will carry out the method of placing the app within the background earlier than terminating it many instances all through the remainder of this tutorial. From this level on, if the tutorial asks you to carry out a chilly launch of the app, that is what it’s best to do.

As soon as the app restarts, observe how the third tab is not chosen. That is an instance of an app that would not restore state.

Example of an app without state restoration

It is time to study a bit extra about how a SwiftUI app’s Scene works now.

Understanding Scene Storage

In SwiftUI, a Scene is a container for views which have their lifecycle managed by the working system. All iOS apps begin with a single Scene. Open AppMain.swift, and you’ll see this for your self.

// 1
struct AppMain: App {
  personal var booksModel = BooksModel()

  // 2
  var physique: some Scene {
    WindowGroup("Hawk Notes", id: "hawk.notes") {

Within the code above, which is already in your app:

  1. AppMain is of kind App. The @essential attribute alerts to the runtime that that is the entry level for the whole app.
  2. The physique property for an App returns a Scene that acts because the container for all views within the app.

To make state restoration very easy, Apple offers a brand new attribute you may add to a property: @SceneStorage.

SceneStorage is a property wrapper that works very equally to the State property wrapper, which you could have used already. Like State, your code can each learn and write to a property attributed with @SceneStorage, and SwiftUI mechanically updates any components of your app that learn from it.

SwiftUI additionally saves the worth of properties attributed with @SceneStorage into persistent storage — a database — when the app is distributed to the background. Then, it mechanically retrieves and initializes the property with that worth when the app enters the foreground once more.

Due to this, SceneStorage is ideal for including state restoration to your apps.

It truly is that easy! So let’s now begin coding.

Saving State

It is time to add some state restoration goodness to the Hawk Notes app. Open ContentView.swift.

Close to the highest of the view, discover the road that defines the chosen tab for the app:

@State var selectedTab = ""

Replace this line to make use of the SceneStorage property wrapper like so:

@SceneStorage("ContentView.CurrentTab") var selectedTab = ""

With this variation, you’ve got up to date the selectedTab property to make use of SceneStorage — fairly than State — with an identifier to make use of as its storage key: ContentView.CurrentTab. The identifier ought to be distinctive inside your app. This lets you create a number of SceneStorage variables which will not conflict with one another.

Construct and run the app. As soon as working, change to the third tab once more. Then carry out a chilly launch of the app that you just realized the right way to carry out earlier.

Restoring the selected tab

How simple was that! By merely altering the attribute on the selectedTab property from @State to @SceneStorage(...), your app now mechanically restores the state appropriately when launched. That was simple!

State restoration in action

Restoring All The Issues

The truth is, it was really easy, why do not you restore state for a couple of extra properties inside the app?

Inside any of the primary three tabs, faucet the View in Amazon button. An online view opens up displaying the e book in Amazon. Chilly launch the app. As anticipated, the working system would not restore the net view.

In Xcode, open BookView.swift. Discover the property declaration for isShowingAmazonPage, and replace it as follows:

@SceneStorage("BookView.ShowingAmazonPage") var isShowingAmazonPage = false

Discover how the identifier is completely different this time.

Construct and run the app once more. Open the Amazon web page for one of many apps. Carry out a chilly launch, and make sure the Amazon web page reveals mechanically after the following launch.

Restore Amazon state after relaunching

Faucet Accomplished to shut the Amazon net view. Write a fast observe for the e book, then faucet Save. The listing of notes shows your observe for the e book. Begin typing a second observe. This time, earlier than tapping Save, carry out a chilly launch. When the app relaunches, discover the way it did not save your draft observe. How annoying!

In Xcode, nonetheless in BookView.swift, discover the declaration for newNote:

@State var newNote: String = ""

And replace it by including the SceneStorage attribute to the property:

@SceneStorage("BookView.newNote") var newNote: String = ""

One other SceneStorage property, with one other completely different identifier.

Construct and run the app once more. Write a draft observe for a e book, carry out a chilly begin, and make sure that relaunching the app restores the draft observe state.

Using state restoration to restore a draft note

Subsequent, open CharacterView.swift. Make an identical change to replace the newNote property as properly, being cautious to offer a special key for the property wrapper:

@SceneStorage("CharacterView.newNote") var newNote: String = ""

Construct and run the app. Navigate to any character, create a draft character observe and carry out a chilly launch. Affirm SceneStorage restores the draft observe state.

State Restoration and the Navigation Stack

Faucet any character to load the character element display. Carry out a chilly launch, and spot how the app did not load the character element display mechanically.

Hawk Notes handles navigation utilizing a NavigationStack. It is a model new API for iOS 16. The app shops the state of the NavigationStack in an array property known as path.

Given how simple it was to revive state to date on this tutorial, you are most likely pondering it is easy so as to add state restoration to the path property — simply change the State attribute to a SceneStorage one. Sadly, that is not the case.

When you strive it, the app will fail to compile with a reasonably cryptic error message:

No precise matches in name to initializer

Attempting to save a complex model object using Scene Storage generates a compiler error

What is going on on? Have a look at the definition for SceneStorage, and spot that it is outlined as a generic struct with a placeholder kind known as Worth:

@propertyWrapper public struct SceneStorage<Worth>

A number of initializers are outlined for SceneStorage, all of which put restrictions on the categories that Worth can maintain. For instance, have a look at this initializer:

public init(wrappedValue: Worth, _ key: String) the place Worth == Bool

This initializer can solely be used if Worth is a Bool.

Wanting by way of the initializers obtainable, you see that SceneStorage can solely save a small variety of easy sorts — Bool, Int, Double, String, URL, Knowledge and some others. This helps guarantee solely small quantities of knowledge are saved inside scene storage.

The documentation for SceneStorage provides a touch as to why this can be with the next description:

“Make sure that the information you employ with SceneStorage is light-weight. Knowledge of enormous dimension, corresponding to mannequin information, shouldn’t be saved in SceneStorage, as poor efficiency might end result.”

This encourages us to not retailer massive quantities of knowledge inside a SceneStorage property. It is meant for use just for small blobs of knowledge like strings, numbers or Booleans.

Restoring Characters

The NavigationStack API expects full mannequin objects to be positioned in its path property, however the SceneStorage API expects easy information. These two APIs do not seem to work properly collectively.

Concern not! It is attainable to revive the navigation stack state. It simply takes a bit extra effort and a little bit of a detour.

Open BookView.swift. Add a property to carry the present scene section beneath the property definition for the mannequin:

@Surroundings(.scenePhase) var scenePhase

SwiftUI views can use a ScenePhase setting variable after they need to carry out actions when the app enters the background or foreground.

Subsequent, create a brand new non-obligatory String property, attributed as scene storage:

@SceneStorage("BookView.SelectedCharacter") var encodedCharacterPath: String?

This property will retailer the ID for the presently proven character.

Dealing with Scene Modifications

Lastly, add a view modifier to the GeometryReader view, instantly following the onDisappear modifier towards the underside of the file:

// 1
.onChange(of: scenePhase) { newScenePhase in
  // 2
  if newScenePhase == .inactive {
    if path.isEmpty {
      // 3
      encodedCharacterPath = nil

    // 4
    if let currentCharacter = path.first {
      encodedCharacterPath =

  // 5
  if newScenePhase == .energetic {
    // 6
    if let characterID = encodedCharacterPath,
      let characterUUID = UUID(uuidString: characterID),
      let character = mannequin.characterBy(id: characterUUID) {
      // 7
      path = [character]

This code might appear like so much, but it surely’s quite simple. This is what it does:

  1. Add a view modifier that performs an motion when the scenePhase property modifications.
  2. When the brand new scene section is inactive — that means the scene is not being proven:
  3. Set the encodedCharacterPath property to nil if no characters are set within the path, or
  4. Set the encodedCharacterPath to a string illustration of the ID of the displayed character, if set.
  5. Then, when the brand new scene section is energetic once more:
  6. Unwrap the non-obligatory encodedCharacterPath to a string, generate a UUID from that string, and fetch the corresponding character from the mannequin utilizing that ID.
  7. If a personality is discovered, add it to the path.

Construct and run the app. Within the first tab, faucet Agatha to navigate to her character element view. Carry out a chilly launch, and this time when the app relaunches, the element display for Agatha reveals mechanically. Faucet again to navigate again to the e book display for The Good Hawk.

Subsequent, faucet the tab for The Damaged Raven. This does not look proper. As quickly because the app masses the tab, it mechanically opens the character view for Agatha, though she should not be within the listing for that e book. What is going on on?

Broken state restoration showing Agatha in every tab

Recognizing That Books Are Distinctive

The important thing to understanding this bug is recognizing that every tab within the app makes use of the identical key for any property attributed with the SceneStorage property wrapper, and thus, all tabs share the property.

The truth is, you may see this similar challenge with all the opposite objects the app has saved for state restoration already. Attempt including a draft observe to any of the books. Carry out a chilly launch and navigate to all three of the books. Discover how the app saves a draft for all of them.

Relying on the performance of your app, this will or is probably not an issue. However for the character restoration, it most actually is an issue. Time to repair it!

First, open ContentView.swift and replace the initialization of BookView to move within the presently chosen tab:

BookView(e book: $e book, currentlySelectedTab: selectedTab)

This may create a warning — however don’t fret — you may repair that subsequent.

Navigate again to BookView.swift, and add the next code instantly underneath the e book property:

// 1
let isCurrentlySelectedBook: Bool

// 2
init(e book: Binding<Guide>, currentlySelectedTab: String) {
  // 3
  self._book = e book
  self.isCurrentlySelectedBook = currentlySelectedTab == e

On this code:

  1. You create a brand new immutable property, isCurrentlySelectedBook which can retailer if this e book is the one presently being displayed.
  2. You add a brand new initializer that accepts a binding to a Guide and the ID of the tab presently chosen.
  3. The physique of the initializer explicitly units the e book property earlier than setting the isCurrentlySelectedBook property if the currentlySelectedTab matches the ID for the e book represented by this display.

Lastly, replace the preview on the backside of the file:

  e book: .fixed(Guide(
    identifier: UUID(),
    title: "The Good Hawk",
    imagePrefix: "TGH_Cover",
    tagline: "It is a tagline",
    synopsis: "It is a synopsis",
    notes: [],
    amazonURL: URL(string: "")!,
    characters: []
  currentlySelectedTab: "1234"

The one distinction with the earlier preview is the addition of the currentlySelectedTab argument.

Construct the app, and now it would compile with none issues.

Updating the Scene Change

Nonetheless in BookView.swift, take away the onChange view modifier you added within the earlier part, and change it with the next:

.onChange(of: scenePhase) { newScenePhase in
  if newScenePhase == .inactive {
    // 1
    if isCurrentlySelectedBook {
      if path.isEmpty {
        encodedCharacterPath = nil

      // 2
      if let currentCharacter = path.first {
        encodedCharacterPath = mannequin.encodePathFor(character: currentCharacter, from: e book)

  if newScenePhase == .energetic {
    if let characterPath = encodedCharacterPath,
      // 3
      let (stateRestoredBook, stateRestoredCharacter) =
        strive? mannequin.decodePathForCharacterFromBookUsing(characterPath) {
      // 4
      if == e {
        // 5
        path = [stateRestoredCharacter]

The construction of the above is similar to the final one you added, with some vital variations:

  1. This time, the app solely saves the character for the e book it shows. The app ignores this logic for all different books.
  2. Subsequent, fairly than saving the ID of the character into scene storage, you name encodePathFor(character:from:) on the e book mannequin. You possibly can view this technique by opening BookModel.swift. It is only a easy operate that takes a Character and a Guide and returns a String formatted as b|book_id::c|character_id. book_id and character_id are the IDs of the e book and character, respectively.
  3. Later, when the view is relaunched, the IDs for the e book and character are decoded after which loaded from the mannequin.
  4. If profitable, the app checks the restored e book ID towards the e book ID for this tab. In the event that they match, it updates the path.

Construct and run the app.

This time, navigate to the primary character in every of the three books. Carry out a chilly launch from the third tab. When the app relaunches, it selects the tab for The Burning Swift and reveals the element view for Girl Beatrice. Navigate to each the opposite e book tabs and spot that the e book view fairly than a personality view is proven.

Detail showing state restoration only occurs for the current tab

Understanding Energetic Customers

Thus far, you’ve got targeted on restoring state from a earlier session when an app launches. One other kind of state restoration can be widespread for iOS apps — restoring from a person exercise.

You will use person exercise, represented by the NSUserActivity class, to revive state when transferring from outdoors your app again into it. Examples embody loading a selected view from a Siri search end result, deep linking from a Fast Notice or performing a Handoff to a different iOS or macOS machine.

In every of those instances, when iOS launches your app, and a person exercise is introduced, your app can use the knowledge from the surface app to set your state appropriately.

Including Window Dressing

Now, you may add help for a number of home windows to Hawk Notes and use NSUserActivity to load the proper content material when the app launches a brand new window.

First, you want to inform iOS that your app helps a number of home windows. Open the Data.plist file. Discover the row with the important thing Utility Scene Manifest, and use the disclosure indicator on the far left of the row to open the contents of the array. Replace the worth for Allow A number of Home windows to YES.

Subsequent, hover over the little up/down arrow within the middle of the final row till a plus icon seems, and click on that to create a brand new row.

Identify the important thing NSUserActivityTypes, and set its kind to Array.

Use the disclosure indicator on the far left of the row to open the — presently empty — array. Then, click on the plus icon once more. This time, Xcode creates a brand new merchandise inside the NSUserActivityTypes array known as Merchandise 0. Set the worth of this row to:


This registers a brand new person exercise kind with iOS and tells it to open Hawk Notes when the app launches from a person exercise with this key.

Updating the Info.plist to support multiple windows

Subsequent, open BookView.swift.

On the very high of the BookView declaration, instantly earlier than defining the mannequin, add the next line:

static let viewingCharacterDetailActivityType = "com.raywenderlich.hawknotes.staterestore.characterDetail"

This is identical key that you just utilized in Data.plist earlier.

Subsequent, find the initialization of the CharacterListRowView view, and add a brand new onDrag view modifier to it:

// 1
.onDrag {
  // 2
  let userActivity = NSUserActivity(activityType: BookView.viewingCharacterDetailActivityType)

  // 3
  userActivity.title = character.title
  userActivity.targetContentIdentifier =

  // 4
  strive? userActivity.setTypedPayload(character)

  // 5
  return NSItemProvider(object: userActivity)

With this code, you are:

  1. Including an onDrag view modifier to every row within the listing of characters. When a row is dragged, you are then:
  2. Creating a brand new NSUserActivity with the important thing outlined earlier.
  3. Setting the title and content material of the exercise to symbolize the character being dragged.
  4. Setting the payload for the person exercise to be the Character represented by that row. setTypedPayload(_:) takes any Encodable object and, together with its decoding counterpart typedPayload(_:), permits for type-safe encoding and decoding of sorts from the UserInfo dictionary.
  5. Lastly, returning an NSItemProvider from the drag modifier. NSItemProvider is just a wrapper for passing info between home windows.

Utilizing the machine selector in Xcode, replace your run vacation spot to an iPad Professional. Construct and run your app.

Selecting an iPad as a run destination

As soon as working, if the iPad is in portrait mode, rotate it to panorama mode utilizing Gadget ▸ Rotate Left from the menu bar.

Drag a personality to the left fringe of the iPad to set off a brand new window earlier than dropping the row.

Basic multi-window support

Your app now helps a number of home windows however, sadly, would not navigate to the chosen character.

To repair that, open BookView.swift and add a brand new view modifier to the GeometryReader:

// 1
) { userActivity in
  // 2
  if let character = strive? userActivity.typedPayload(Character.self) {
    // 3
    path = [character]

With this code, you:

  1. Register your BookView to obtain any person exercise with the important thing from earlier.
  2. Try to decode a Character occasion from the payload, utilizing the decoding half of the type-safe APIs mentioned above.
  3. Then, set the trail for use by the NavigationStack to comprise the Character you simply decoded.

Deep linking to the correct Character when opening a second window

Lastly, open ContentView.swift and repeat the above, however this time, restoring the state for which e book the app ought to show within the tab view.

Add the next view modifier to the TabView:

// 1
.onContinueUserActivity(BookView.viewingCharacterDetailActivityType) { userActivity in
  // 2
  if let character = strive? userActivity.typedPayload(Character.self), let e book = mannequin.e book(introducing: character) {
    // 3
    selectedTab = e

This code:

  1. Registers ContentView to obtain any person exercise tagged with the viewingCharacterDetailActivityType kind.
  2. Makes an attempt to decode a Character from the person exercise payload, then fetches the e book that introduces that character.
  3. If a e book is discovered, units the suitable tab.

Deep linking to the correct tab when opening a second window

Construct and run your app. Choose the second tab. Drag any character to create a brand new window and make sure the proper tab shows when it opens.

You probably did it! That is the top of the tutorial and you’ve got realized all about state restoration with SwiftUI!

The place to Go From Right here?

You need to use the Obtain Supplies button on the high or backside of this tutorial to obtain the starter and last tasks.

Congratulations! You have realized how simple it’s so as to add state restoration to your app utilizing the SceneStorage modifier and NSUserActivity.

You have seen how highly effective SceneStorage could be for restoring easy information sorts, but in addition how you will have a bit extra work to do if you happen to plan to reuse the identical View in a number of locations, like tabs in a TabView, or if you want to restore advanced sorts like mannequin objects.

Alongside the way in which, you touched on some extra superior subjects corresponding to generics and property declaration attributes like @State and @SceneStorage.

You have additionally used the brand new NavigationStack launched with iOS 16, and seen one option to work round issues brought about when an API with stronger kind security, NavigationStack, interacts with an API that prefers easy information sorts, SceneStorage.

And most significantly, you’ve got been launched to Jamie, Agatha, Sigrid and all a very powerful characters from the Shadow Skye trilogy!

We hope you loved this tutorial, and when you’ve got any questions or feedback, please be a part of the discussion board dialogue under!


Leave a Reply