iOS 从后台返回时不会调用 viewWillAppear,即使 UIModalPresentationStyle.FullScreen,在 iOS 13+

iOS viewWillAppear not being called when returning from background, even with UIModalPresentationStyle.FullScreen, in iOS 13+

为什么当我们的应用程序从后台返回时 iOS 不调用 viewWillAppear,即使我已设置 UIModalPresentationStyle.FullScreen

viewWillAppear 是一个响应视图控制器状态变化的函数。背景和前景状态不同;它们是在应用级别完成的。

您仍然可以使用通知响应应用状态更改:

override func viewDidAppear(_ animated: Bool) {
    // ...
    NotificationCenter.default.addObserver(self, selector: #selector(didReceiveForegroundNotification), name: UIApplication.willEnterForegroundNotification, object: nil)
}

@objc func didReceiveForegroundNotification() {
    // app returned from the background
}

您的视图控制器将监听事件,直到它作为观察者被解除分配或删除。如果不想在视图控制器消失时执行代码,可以在 viewDidDisappear:

上执行
override func viewDidDisappear(_ animated: Bool) {
    // ..
    NotificationCenter.default.removeObserver(self)
}