遍历多个 UIAlertController

Loop over multiple UIAlertController's

在某些情况下,我的应用程序需要显示多个警报消息。错误消息在启动时收集,需要一次一条地显示给用户。当第一个被确认时,下一个应该被呈现。显然,问题是它们都试图同时执行。有没有一种聪明的方法可以同步执行此操作?下面是一些简单描述我想做什么的代码:

var errors : [NSError]!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let error1 = NSError(domain: "Test1", code: 1, userInfo: [NSLocalizedFailureReasonErrorKey : "Test1 reason."])

    let error2 = NSError(domain: "Test2", code: 2, userInfo: [NSLocalizedFailureReasonErrorKey : "Test2 reason."])

    let error3 = NSError(domain: "Test3", code: 2, userInfo: [NSLocalizedFailureReasonErrorKey : "Test3 reason."])

    errors = [error1, error2, error3]

}

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

    for error in errors {

        self.showAlert(error)

    }

}

func showAlert(error: NSError) {

    var alert = UIAlertController(title: error.domain, message: error.localizedDescription, preferredStyle: .Alert)
    alert.addAction(UIAlertAction(title: "OK", style: .Default, handler:nil))

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

你快到了。拥有警报消息缓冲区是正确的想法。但不是立即显示所有警报,您应该将 showAlert() 调用移至 UIAlertAction 的处理程序。因此,如果解除一个警报,将显示下一个警报。

像这样:

var errors : [NSError]!

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

    let error1 = NSError(domain: "Test1", code: 1, userInfo: [NSLocalizedFailureReasonErrorKey : "Test1 reason."])
    let error2 = NSError(domain: "Test2", code: 2, userInfo: [NSLocalizedFailureReasonErrorKey : "Test2 reason."])
    let error3 = NSError(domain: "Test3", code: 2, userInfo: [NSLocalizedFailureReasonErrorKey : "Test3 reason."])

    errors = [error1, error2, error3]

    showError() // show an alert if errors are queued
}

func showError() {
    if let error = errors.first {
        let alert = UIAlertController(title: error.domain, message: error.localizedDescription, preferredStyle: .Alert)
        let okayAction = UIAlertAction(title: "OK", style: .Default) { action in
            self.errors.removeAtIndex(0) // remove the message of the alert we have just dismissed

            self.showError() // show next alert if there are more errors queued
        }
        alert.addAction(okayAction)
        presentViewController(alert, animated: true, completion: nil)
    }
    else {
        println("All alerts shown")
    }
}

忠告:关闭多个警报非常烦人。也许您可以创建一个专用的全屏 viewController 来显示 UITableView 或其他内容中的所有错误消息。这当然取决于典型用户将看到的警报消息的数量。如果它经常超过三个,我会使用模态 UIViewController,它一目了然地显示所有消息。