Reputation: 392
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()
}
}
}
Upvotes: 2
Views: 1333
Reputation: 7744
Update:
Initializers are called when the view needs to be constructed. This can have different reasons.
Including:
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
Upvotes: 3