Home > front end >  Instances when SwiftUIApp.init() is called?
Instances when SwiftUIApp.init() is called?

Time:01-25

I recently migrated from using the AppDelegate to just using the SwiftUI App lifecycle. But in some cases, when my app has been in the background for quite some time (maybe even terminated by the os to free up memory), it doesn't seem like the initialize method is called.

@main
struct MyApp: App {
    
    init() {
        // Expected:
        // This method is called whenever:
        // 1. Application is launched (cold start)
        // 2. Application is terminated due to memory, and user launches application again
        // 3. Applicaiton is inactive, and becomes active again
    }
    
    var body: some Scene {
        WindowGroup {
            SplashView()
        }
    }
}

CodePudding user response:

Update:

Initializers are called when the view needs to be constructed. This can have different reasons.

Including:

  • the view is initialized the first time
  • state changes force the view to be rebuild

But there also is caching involved. So you shouldn´t rely on the initializer to update data.

/Update

In SwiftUI lifecycle you want to react to state changes:

@main
struct MyApp: App {
@Environment(\.scenePhase) private var scenePhase


var body: some Scene {
    WindowGroup {
        MyRootView()
    }
    .onChange(of: scenePhase) { phase in
        if phase == .background {
            // Perform cleanup when all scenes within
            // MyApp go to the background.
        }
    }
}
}

reference: https://developer.apple.com/documentation/swiftui/scenephase

  •  Tags:  
  • Related