I am currently working on SwiftUI app in which I am using SceneDelegate
and AppDelegate
. I would like to know how I can convert the life cycle from
where does the SceneDelegate code goes.
@available(iOS 14.0, *)
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
WindowGroup { // << this is a scene
ContentView()
.onChange(of: scenePhase) { phase in
switch phase {
case .active:
print(">> your code is here on scene become active")
case .inactive:
print(">> your code is here on become inactive")
case .background:
print(">> your code is here on go in background")
default:
print(">> do something else in future")
}
}
}
}
}
Set the environment on the ContentView as follows:
import SwiftUI
import CoreData
@main
struct MasterDetailApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView().environment(\.managedObjectContext, appDelegate.persistentContainer.viewContext)
}
}
}