如何检查视图控制器是否已在 Swift 中被关闭

How to check if a view controller has been dismissed in Swift

如果我像这样呈现 ViewController

let authViewController = authUI!.authViewController()
authViewController.modalPresentationStyle = .overCurrentContext
self.present(authViewController, animated: true, completion: nil)

我想知道 ViewController 何时被解雇。我尝试了以下方法:

let authViewController = authUI!.authViewController()
authViewController.modalPresentationStyle = .overCurrentContext
self.present(authViewController, animated: true, completion: {
   print("View Dismissed")
})

但这只会让我知道视图是否已成功呈现。此 ViewController 不是我创建的,因此我无法更改 viewWillDissapear 方法。

整个答案基于 OP 无法访问 authViewController 代码的假设

如果您无权访问 authViewController 代码,糟糕的解决方案是使用视图控制器的 viewWillAppear 来查找何时取消授权视图控制器。

基本上,当您 present/push 任何 viewController 覆盖现有的视图控制器时,当 presented/pushed 视图控制器被关闭或弹出时,您的视图控制器的 viewWillDisappear 将被类似地调用out viewWillAppear 将被调用。

因为 viewWillAppear 也可能因其他原因被调用,您不想将其混淆为 authViewController 解雇,请使用布尔值

private var shouldMonitorAuthViewControllerDismiss = false //declared a instance property

当您实际呈现 authViewController

时,将布尔值设置为 true
let authViewController = authUI!.authViewController()
authViewController.modalPresentationStyle = .overCurrentContext
self.present(authViewController, animated: true, completion: {
    shouldMonitorAuthViewControllerDismiss = true
})

终于在你的 viewWillAppear

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        if shouldMonitorAuthViewControllerDismiss {
            //auth view controller is dismissed
        }
        shouldMonitorAuthViewControllerDismiss = false
    }