@UIApplicationDelegateAdaptor

SwiftUI iOS有了一个全新的生命周期,完全放弃了 UIKit 的应用程序和场景托付,可是有时需求运用UIKit 中UIApplicationDelegate的传统协议:处理推送通知的注册、呼应内存警告、检测时间更改等,运用UIApplicationDelegate就可以完成。

假如需求拜访SwiftUI iOS中AppDelegate的功用,您应该创立一个承继自NSObject 的类 UIApplicationDelegate 和协议的类,并为其提供功用。

1、完成AppDelegate协议:创立一个承继NSObject并符合UIApplicationDelegate协议的类

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        return true
    }
}

2、运用AppDelegate :在main->App-> Scene中运用UIApplicationDelegateAdaptor特点包装器

@main
struct YdtApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

UIApplicationDelegateAdaptor 与 ObservableObject 结合

1、让AppDelegate承继ObservableObject协议

class AppDelegate: NSObject, UIApplicationDelegate, ObservableObject {
    @Published var value: String = ""
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        self.value = "AppDelegate"
        return true
    }
}

2、经过环境托付(EnvironmentObject)特点包装器拜访AppDelegate的值

struct ContentView: View {
    @EnvironmentObject var appDelegate: AppDelegate  
    var body: some View {
       Text("Value: (appDelegate.value)")  
    }
}

@NSApplicationDelegateAdaptor

在上面运用 @UIApplicationDelegateAdaptor 特点包装器来绑定 UIApplicationDelegate 类。可是UIApplicationDelegate 类在 macOS 上不可以运用,我们应该运用 @NSApplicationDelegateAdaptor特点包装器来完成功用

1、完成AppDelegate协议 NSApplicationDelegate NSWindowDelegate

private final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
    var window: NSWindow?
    func applicationDidFinishLaunching(_ notification: Notification) {
        NSApp.delegate = self
        window = NSApplication.shared.windows[0]
        window?.isReleasedWhenClosed = false
        window?.delegate = self
    }
    func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
        window?.makeKeyAndOrderFront(self)
        return true
    }
    @objc func openMainWindow(_ sender: AnyObject?) {
        window?.orderFrontRegardless()
    }
}

留意:

一定要添加 NSApp.delegate = self,否则点击Dock图标无法进入applicationShouldHandleReopen方法,就会创立新的NsWindow

2、运用AppDelegate

@main
struct MyApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}