NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

How to run code when your app launches

Paul Hudson    @twostraws   

Updated for Xcode 12.5

New in iOS 14

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

Hacking with Swift is sponsored by Emerge

SPONSORED Emerge helps iOS devs write better, smaller apps by profiling binary size on each pull request and surfacing insights and suggestions. Companies using Emerge have reduced the size of their apps by up to 50% in just the first day. Built by a team with years of experience reducing app size at Airbnb.

Set up a demo!

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

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.