iOS响应事件解除了UIAlertController

我有一个情况,我想呈现一个UIAlertController为了等待一个事件(从第三方数据asynchronous请求)完成显示我的主要ViewController的用户进行交互之前。

一旦asynchronous代码完成,那么我想closuresUIAlertController 。 我知道,通常UIAlertControllers设置了一个button来解除它,这是从用户input。 我想知道我想做什么(不考虑用户input的事件)是可能的?

到目前为止,我试图展示UIAlertController ,然后在while循环中等待事件发生时检查布尔值。

 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) 

这给出了一个警告

警告:正在进行演示或解散时尝试从视图控制器中解散!

并且不closuresUIAlertController。 我也试过alert.dismissViewControllerAnimated(true, completion: nil)而不是self.dismissViewControllerAnimated(true, completion: nil) ,但是这并没有摆脱UIAlertController

我不会使用一个while循环,但为您的dataLoadingDone属性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 }) } } 

另一个用户(马特)给了我相当肯定的答案,但是他把它删除了,所以我要回答它。 只是想给(虽然他似乎很有信誉)。

他写的是我的UIAlertController演示文稿没有完成之前,我试图解雇它,所以我得到了这个错误。 我将我的代码更改为以下内容:

 // check if I need to wait at all if (!dataLoadingDone) { var alert = UIAlertController(title: "Please wait", message: "Retrieving data", preferredStyle: UIAlertControllerStyle.Alert) self.presentViewController(alert, animated: true, completion: { () -> Void in // moved waiting and dismissal of UIAlertController to inside completion handler while (!self.dataLoadingDone) { } self.dismissViewControllerAnimated(true, completion: nil) }) } 

我把等待和解雇移到了presentViewController调用的完成处理程序中,这样我就知道提交是在解散之前完成的。 此外,我检查是否需要等待第一个if语句,否则会发生另一个问题,如果while循环从不执行任何操作。

我还没有100%的确定,因为我的布尔值此刻实际上从来没有错(数据检索真的很快)。 不过,我有理由相信在我的应用程序开发中需要更长的时间,所以我会在这里更新答案。

编辑:以前发布答案(亚伦金)另一个用户也是正确的关于while循环阻塞。 我以为while循环与其他事件共享处理时间,但显然不是(或者至less没有足够的时间)。 因此,上述while循环不起作用