关闭一个 View Controller,然后呈现一个 Alert Controller

Dismissing a View Controller, then presenting an Alert Controller

在我的项目中,我使用 rootViewController?.dismiss 将一些 View Controller 解散回主 VC。

在完成处理程序中,我想在主视图控制器再次可见时在其上显示一个 UIAlertController。

我的问题是 UIAlertController 从未出现。我的直觉是因为我在 launchFrom 参数中使用了 self。我是否需要获取对主 VC 的引用并将其显示在那里?

关闭 VC 并尝试显示警报:

self.view.window!.rootViewController?.dismiss(animated: false, completion: {
    Constants.presentThankYou(launchFrom: self)
})

呈现ThankYou方法

static func presentThankYou(launchFrom: UIViewController) {
    let alertController = UIAlertController(title: "Thank You!", message: "You did it!", preferredStyle: UIAlertControllerStyle.alert)
    let okAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
        print("Done")
    }
    alertController.addAction(okAction)
    launchFrom.present(alertController, animated: true, completion: nil)
}

在我的所有 VC 都被关闭后如何显示警报控制器?

我脑子里乱七八糟的, 尝试在 viewDidAppear 中进行。为了防止警报一直出现,请使用 bool shouldShowThankYouAlert 并在 dismiss completion 处理程序

中将此值设置为 true

所以有一个问题,完成块不需要主线程。我建议强制完成执行一些代码。

var topController: UIViewController? {
  if var temp = UIApplication.shared.keyWindow?.rootViewController {
    while let presentedViewController = temp.presentedViewController {
      temp = presentedViewController
    }
    return temp
  }
  return nil
}

self.view.window!.rootViewController?.dismiss(animated: false, completion: {
  DispatchQueue.main.async {
    guard let top = topController else { return }
    Constants.presentThankYou(launchFrom: top)
  }
})

如果需要也可以参考这个,调用alert在Controller的viewWillDisappear中显示被dismissed即可

override func viewWillDisappear(_ animated: Bool) {
        if self.isMovingFromParentViewController {
            DispatchQueue.main.async {
                wrapperClass.BasicAlert("View is Dismissed", message: "", view: self)
            }
        }
    }

这将在完全关闭视图时显示警报

我没有检查,但是使用 window 代替 UIViewController 怎么样?

self.view.window!.rootViewController?.dismiss(animated: false, completion: {
   Constants.presentThankYou()
})

static func presentThankYou() {
   let alertController = UIAlertController(title: "Thank You!", message: "You did it!", preferredStyle: UIAlertControllerStyle.alert)
   let okAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
       print("Done")
    }
   alertController.addAction(okAction)
   appDelegate.window.present(alertController, animated: true, completion: nil)
}