我有这样一种情况,我想呈现一个 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/