How to run code when your app launches
How to run code when your app launches êŽë š
Updated for Xcode 15
When you're using the SwiftUI App life cycle, your app launches through one struct that conforms to the App
protocol. Its job is to create your initial view using either WindowGroup
, DocumentGroup
, or similar, but because its created before any of your actual views this is the perfect place for running code when your app launches.
For example, if you wanted to set up some initial UserDefaults
values, your app's initializer is a great place to call register(defaults:)
. This method sets up default defaults, by which I mean initial values for UserDefaults
values that exist only until you set them â as soon as you provide a value of your own, these aren't used any more, and these initial values also disappear when your app is terminated so you should call it every launch just to make sure.
So, we might write something like this:
@main
struct ExampleApp: App {
// register initial UserDefaults values every launch
init() {
UserDefaults.standard.register(defaults: [
"name": "Taylor Swift",
"highScore": 10
])
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
That initializer()
is run before the body
property is called, so it's also before ContentView
is called. As a result, any places where you read UserDefaults
in ContentView
will already have your defaults in place.
To demonstrate this, here's an example ContentView
struct that uses @AppStorage
to read the ânameâ key:
struct ContentView: View {
@AppStorage("name") var name = "Anonymous"
var body: some View {
Text("Your name is \(name).")
}
}
Using @AppStorage
requires that we give our property an initial value, which is cumbersome because we need to ensure we have the same initial value everywhere the property is used.
However, here it doesn't matter: âAnonymousâ will only be used for times when no value exists, and no initial defaults have been registered. We already called register(defaults:)
in our app's initializer, so this view will show âYour name is Taylor Swift.â