Skip to main content

How to run code when your app launches

About 3 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to run code when your app launches 관련

SwiftUI by Example

Back to Home

How to run code when your app launches | SwiftUI by Example

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).")
    }
}

Download this as an Xcode projectopen in new window

The text “Your name is Taylor Swift.”.
The text “Your name is Taylor Swift.”.

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.”

Similar solutions…
How to control which view is shown when your app launches | SwiftUI by Example

How to control which view is shown when your app launches
How to run some code when state changes using onChange() | SwiftUI by Example

How to run some code when state changes using onChange()
How to use Instruments to profile your SwiftUI code and identify slow layouts | SwiftUI by Example

How to use Instruments to profile your SwiftUI code and identify slow layouts
How to run an asynchronous task when a view is shown | SwiftUI by Example

How to run an asynchronous task when a view is shown
How to run a completion callback when an animation finishes | SwiftUI by Example

How to run a completion callback when an animation finishes

이찬희 (MarkiiimarK)
Never Stop Learning.