iOS 关闭 UIAlertController 以响应事件

标签 ios swift uialertcontroller

我有这样一种情况,我想呈现一个 UIAlertController 以便在显示我的主要 ViewController 之前等待事件(来自第三方的异步数据请求)完成> 与用户进行交互。

异步代码完成后,我想关闭 UIAlertController。我知道通常 UIAlertControllers 设置有一个按钮来关闭它,这是用户输入的。我想知道我想做什么(通过事件而不是用户输入来关闭)是否可行?

到目前为止,我尝试显示 UIAlertController,然后在 while 循环中等待检查​​事件何时发生的 bool 值:

var alert = UIAlertController(title: "Please wait", message: "Retrieving data", preferredStyle: UIAlertControllerStyle.Alert)

self.presentViewController(alert, animated: true, completion: nil)

// dataLoadingDone is the boolean to check   
while (!dataLoadingDone) {

}

self.dismissViewControllerAnimated(true, completion: nil)

这是一个警告

警告:在演示或解散过程中尝试从 View Controller 中解散!

并且不会关闭 UIAlertController。我还尝试了 alert.dismissViewControllerAnimated(true, completion: nil) 而不是 self.dismissViewControllerAnimated(true, completion: nil),但这并没有摆脱 UIAlertController 或者。

最佳答案

我不会为您的 dataLoadingDone 属性使用 while 循环,而是使用 didSet 观察器。因此,您可以尝试类似于以下代码的操作:

class ViewController: UIViewController {

    var dismissAlertClosure: (() -> Void)?
    var dataLoadingDone = false {
        didSet {
            if dataLoadingDone == true {
                dismissAlertClosure?()
            }
        }
    }


    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        let alert = UIAlertController(title: "Please wait", message: "Retrieving data", preferredStyle: .Alert)
        presentViewController(alert, animated: true, completion: nil)

        // Set the dismiss closure to perform later with a reference to alert
        dismissAlertClosure = {
            alert.dismissViewControllerAnimated(true, completion: nil)
        }

        // Set boolValue to true in 5 seconds in order to simulate your asynchronous request completion
        var dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(5.0 * Double(NSEC_PER_SEC)))
        dispatch_after(dispatchTime, dispatch_get_main_queue(), { self.dataLoadingDone = true })
    }

}

关于iOS 关闭 UIAlertController 以响应事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30489828/

相关文章:

ios - 设备从休眠状态唤醒后后台位置更新未恢复

ios - 如何在 SwiftUI 中将 View() 作为列表的一部分传递?

ios - 相同的 View Controller 加载两次

ios - 静态方法中的 UIAlertController 给出错误 : extra argument animated in cell

使用自定义单元格快速显示警报

iphone - iOS 6 中的镶边/回声/混响效果

ios - 设置值 :forKey: Sets All Values for Specified Index

ios - 刚从 View Controller 面板, Storyboard 中拖动后,uitableview 上方的 xcode 9 额外填充

swift - 将 NSTimer 应用于 UILabel (Swift)

ios - 在类型为 'bounds' 的对象上找不到 UIAlertController 错误 '__strong id'