【发布时间】:2017-06-26 15:34:28
【问题描述】:
我有一个异步调度,我希望屏幕上会弹出 4 个警报。然后每个警报都会在显示新警报之前被解除。 (我在警报之间设置了 3 秒延迟)
class ViewController: UIViewController {
var counter = 1
override func viewDidLoad() {
super.viewDidLoad()
for _ in 1...4{
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0 * Double(counter) , execute: {
print("called")
self.showAlert()
})
}
}
func showAlert(){
let alert = UIAlertController(title: "sampleTitle \(counter)", message: "sampleMessage \(counter)", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
counter += 1
if self.presentedViewController != nil {
dismiss(animated: true, completion: nil)
UIApplication.topViewController()?.present(alert, animated: true, completion: nil)
}else{
UIApplication.topViewController()?.present(alert, animated: true, completion: nil)
}
}
}
问题1:但由于某种原因,整个for loop 被执行,中间没有任何延迟。我猜我不理解主队列是串行队列的一些事情。
问题 2: 即使我关闭了presentedViewController,我也会在控制台中获得以下日志。
called
called
called
called
2017-06-26 11:10:57.000 topViewAndAlertTest[3360:210226] Warning: Attempt to dismiss from view controller <topViewAndAlertTest.ViewController: 0x7fe630c03350> while a presentation or dismiss is in progress!
2017-06-26 11:10:57.001 topViewAndAlertTest[3360:210226] Warning: Attempt to present <UIAlertController: 0x7fe630c04180> on <UIAlertController: 0x7fe630f06fe0> while a presentation is in progress!
2017-06-26 11:10:57.001 topViewAndAlertTest[3360:210226] Warning: Attempt to dismiss from view controller <topViewAndAlertTest.ViewController: 0x7fe630c03350> while a presentation or dismiss is in progress!
2017-06-26 11:10:57.001 topViewAndAlertTest[3360:210226] Warning: Attempt to present <UIAlertController: 0x7fe630c06b40> on <UIAlertController: 0x7fe630f06fe0> while a presentation is in progress!
仅供参考,我的 topviewcontroller 正在使用来自 answer 的代码
问题 3:只有 2 个警报弹出...我从来没有看到第 3、4 个警报!
编辑:
经过rmaddy的建议,我的错误略有改变:
called
called
called
called
2017-06-26 11:59:33.417 topViewAndAlertTest[4834:441163] Warning: Attempt to dismiss from view controller <topViewAndAlertTest.ViewController: 0x7fb596d05a30> while a presentation or dismiss is in progress!
2017-06-26 11:59:33.417 topViewAndAlertTest[4834:441163] Warning: Attempt to dismiss from view controller <topViewAndAlertTest.ViewController: 0x7fb596d05a30> while a presentation or dismiss is in progress!
我少收到 2 个警告。但仍然:一旦警报 1 出现在屏幕上,警报 2 就会将其关闭,仅此而已!没有延迟没有第三,第四警报!
【问题讨论】:
标签: ios swift grand-central-dispatch uialertcontroller dispatch-async