Celebrating 200 Daily Coding Tips 🎉 all tutorials will be free to all this week!
The difference between @SceneStorage
and @AppStorage
is that @AppStorage
uses UserDefaults
as the location for saving data.
In this app, I’m going to be saving every kind of data that I can with this property wrapper. The first thing I’m doing is creating CustomType
, which conforms to the Codable
protocol. This stores all the data from all of my controls, because I wanted a way to demonstrate that Data
is one of the types supported by @SceneStorage
.
This creates the possibility of storing a variety of data, as long as it can be converted into JSON data using JSONEncoder
.
The customType
computed property automatically decodes the JSON data from @SceneStorage
if it can, otherwise returning nil
.
Now I’m going to create a body
property for my ContentView
type.
This is where I’ll add controls that allow me to change the data, most of which save automatically to @SceneStorage
. The only exception to this is URL, which doesn’t have an easy way of modifying its value. My solution for this was to update the URL when the CustomType
object is saved, which is done by a Button
.
The saved value of the CustomType
is shown in its own Section
if it exists.
This data will persist when the app is restarted, and creating multiple windows on iPad will allow you to edit these values separately without them changing each other. In other words, every screen that can be displayed to the user can have its own distinct storage, without any problems caused by data changing in the wrong place.