尝试在ViewController上呈现UIViewController,它已经呈现了UIAlertController

时间:2016-06-19 08:26:05

标签: ios xcode swift uiviewcontroller uialertcontroller

我刚接触swift iOS编程。我写了一些代码。简单来说,我想执行警报,然后通过" performSegueWithIdentifier"移动到另一个视图控制器。但我得到了这个输出:

"警告:尝试在Kilaundry.ViewController上呈现UIViewController:0x7fa05b72dd60:0x7fa05b49a2c0已经呈现UIAlertController:0x7fa05d859d70"

我认为警告是在这段代码之后:" NSOperationQueue.mainQueue()。addOperationWithBlock"。

为什么我无法执行提醒,然后通过" performSegueWithIdentifier&#34 ;?移动到另一个视图控制器?请帮我找出这个警告发生的原因。

这是我的代码:

                        if let data = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
                            print(jsonResult)

                            Resp_code = jsonResult["Resp_code"] as? String;
                            Resp_message = jsonResult["Resp_message"] as? String;

                            if Resp_code == "01" {
                                NSOperationQueue.mainQueue().addOperationWithBlock {
                                    let alert = UIAlertController(title: "Information", message:Resp_message!, preferredStyle: .Alert)
                                    alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
                                    self.presentViewController(alert, animated: true){}
                                    self.performSegueWithIdentifier("LoginSucceed", sender: self)
                                }
                            } else {

                                NSOperationQueue.mainQueue().addOperationWithBlock {
                                let alert = UIAlertController(title: "Oops!", message:"It seems "+Resp_message!, preferredStyle: .Alert)
                                alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
                                self.presentViewController(alert, animated: true){}
                                }
                            }
                        }

1 个答案:

答案 0 :(得分:3)

您收到此错误是因为您试图在已经显示模态VC的视图控制器上呈现模态视图控制器 - 您提供警报控制器,然后立即触发segue(可能也是模态) 。 视图控制器在给定时间只能有一个呈现视图控制器。做你想做的最简单的方法就是提出“好”的方法。由" LoginSucceeded"提供的VC上的警报SEGUE。

但是,我会重新考虑你是否应该显示警报。我建议你阅读official Apple guidelines on the use of alerts - 除非你真的需要,否则基本上不会显示警告。特别是,不要显示警报以通知用户应用程序正常运行。 在请求失败时显示错误警报是正确的 - 在用户无需成功登录时显示错误警告。