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

孤者浪人 提交于 2020-08-23 05:45:24

问题


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 UIKit to SwiftUI one where there is an App struct and with scenes etc.

Also I would like to know how to cater for CoreData and PersistentContainers and inject these into our environments.

Also I have used UIApplicationDelegateAdapter to inject AppDelegate but the @main is giving me error

'main()' is only available in iOS 14.0 or newer

I am using @available (iOS 14.0, *) in the beginning:

import SwiftUI

@available(iOS 14.0, *)
@main

struct MyApp: App {

    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Doing it like this, where does the SceneDelegate code goes. I am still quite confused how this conversion goes. I have not seen Apple talking about this in their sessions or anything. Help will be really appreciated.


回答1:


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)
        }
    }
}



回答2:


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")
             }
          }
        }
    }
}


来源:https://stackoverflow.com/questions/62562659/how-to-convert-from-uikit-life-cycle-to-swiftui-life-cycle-in-ios-14-xcode-12-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!