【问题标题】:Attempt to present UIViewController on ViewController which is already presenting UIAlertController尝试在已经呈现 UIAlertController 的 ViewController 上呈现 UIViewController
【发布时间】:2016-10-20 16:38:34
【问题描述】:

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

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

我认为警告在此代码之后:“NSOperationQueue.mainQueue().addOperationWithBlock”。

为什么我不能执行警报然后通过“performSegueWithIdentifier”移动到另一个视图控制器?请帮助我找出为什么会出现此警告。

这是我的代码:

                        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){}
                                }
                            }
                        }

【问题讨论】:

  • 你为什么使用 NSOperation 队列?如果你想在主线程上使用它,我认为你想使用 dipatch_get_main_queue() 。 ://

标签: ios xcode swift uiviewcontroller uialertcontroller


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    相关资源
    最近更新 更多