How to convert from UIKit life cycle to SwiftUI life cycle in iOS 14 (Xcode 12 Beta)

后端 未结 2 989
花落未央
花落未央 2021-01-02 17:11

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

相关标签:
2条回答
  • 2021-01-02 17:37

    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")
                 }
              }
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-02 17:48

    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)
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题