处理关闭和终止应用程序事件 (SwiftUI)

Handling close and terminate app events (SwiftUI)

如何在 SwiftUI 中处理关闭和终止应用程序事件?

View
{
    ...
}.onDisappear {
    //My code
}

仅在我更改视图时工作,在我关闭或终止我的应用程序时不工作。

您可以使用 UIApplication.willTerminateNotification:

NotificationCenter.default.addObserver(forName: UIApplication.willTerminateNotification, object: nil, queue: .main) { _ in
    // terminating
}

这个答案可以更好地解释如何在 SwiftUI 中使用它:

您应该使用 .onReceive 修饰符并像这样订阅您想要的通知:

  YourView()
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.didEnterBackgroundNotification), perform: { output in
                    //Did enter background
         })

您可以使用 UIApplicationDelegate 通知和 UIScene 通知

文档: