iOS 14中,SwiftUI apps遵循App protocol,没有遵循UIApplicationDelegate,但是一些场景需要用到旧的Appdelegate中的生命周期函数,比如push注册,内存警告处理等。
1.首先,创建一个类遵循UIApplicationDelegate
代码语言:javascript复制class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
//add code when didFinishLaunchingWithOptions
return true
}
}
这里以didFinishLaunchingWithOptions为例,可以增加任何UIApplicationDelegate包含的函数。
2.使用UIApplicationDelegateAdaptor属性修饰器,指定你创建的Appdelegate
代码语言:javascript复制@main
struct NewIn14App: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}