NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

How to run code when your app launches

Paul Hudson    @twostraws   

Updated for Xcode 14.2

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 project

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

Hacking with Swift is sponsored by Waldo

SPONSORED Thorough mobile testing hasn’t been efficient testing. With Waldo Sessions, it can be! Test early, test often, test directly in your browser and share the replay with your team.

Try for free today!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.7/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.