关闭 View Controller 后显示警报

Present alert after dismissing View Controller

我使用的是最新的 XcodeSwift 版本。

我正在展示一个特定的 View Controller 像这样:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let contactViewController = storyboard.instantiateViewController(identifier: "contactViewController")
show(contactViewController, sender: self)

我要这样驳回 View Controller

self.presentingViewController?.dismiss(animated: true, completion: nil)

我想在关闭 View Controller 后立即显示 UIAlertController

这个:

self.presentingViewController?.dismiss(animated: true, completion: nil)

let alertMessage = UIAlertController(title: "Your message was sent", message: "", preferredStyle: .alert)
let alertButton = UIAlertAction(title: "Okay", style: UIAlertAction.Style.default)
alertMessage.addAction(alertButton)
self.present(alertMessage, animated: true, completion: nil)

…当然是行不通的,因为我不能在 View Controller.

上提出 UIAlertController

View Controller 被关闭后呈现此 UIAlertController 的最佳方式是什么?

您可以通过像这样获取顶级控制器在完成处理程序中完成此操作

self.presentingViewController?.dismiss(animated: true, completion: {
            let alertMessage = UIAlertController(title: "Your message was sent", message: "", preferredStyle: .alert)
               let alertButton = UIAlertAction(title: "Okay", style: UIAlertAction.Style.default)
               alertMessage.addAction(alertButton)
            UIApplication.getTopMostViewController()?.present(alertMessage, animated: true, completion: nil)
        })

使用这个扩展

extension UIApplication {

    class func getTopMostViewController() -> UIViewController? {
        let keyWindow = UIApplication.shared.windows.filter {[=11=].isKeyWindow}.first
        if var topController = keyWindow?.rootViewController {
            while let presentedViewController = topController.presentedViewController {
                topController = presentedViewController
            }
            return topController
        } else {
            return nil
        }
    }
}

使用 Jawad Ali 的扩展程序,我们可以锚定当前呈现的 ViewController。

如果您想稍后关闭该警报,您可以在另一个完成处理程序中执行此操作,如下面的代码所示。在我的例子中,我将一首歌保存到一个播放列表并关闭该播放列表并显示一个短时间提醒让用户知道保存正常。

DispatchQueue.main.async {
    self?.removeSpinner()
    self?.dismiss(animated: true, completion: {
        let alert = UIAlertController(title: "Save to playlist", message: nil, preferredStyle: .alert)
        UIApplication.getTopMostViewController()?.present(alert, animated: true, completion: {
            Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { _ in
                alert.dismiss(animated: true)
            }
        })
    })
}