尝试在<viewcontroller:>上显示<uialertcontroller:>,其视图不在窗口层次结构中

时间:2016-03-28 15:07:47

标签: ios swift alert uialertaction researchkit

我正在使用ResearchKit开发项目,因此我将用户发送到我创建的任务中:

let taskViewController = ORKTaskViewController(task: SurveyTask, taskRunUUID: nil)
taskViewController.delegate = self
presentViewController(taskViewController, animated: true, completion: nil)

当用户完成调查后,他会进入:

func taskViewController(taskViewController: ORKTaskViewController, didFinishWithReason reason: ORKTaskViewControllerFinishReason, error: NSError?) {
    switch reason {
        case .Completed:

... }

我尝试在

之前显示提醒时遇到问题
taskViewController.dismissViewControllerAnimated(true, completion: nil)

我收到以下错误:

尝试在ViewController上呈现UIAlertController:...:...视图不在窗口层次结构中

在解除ViewController之前,我是否知道如何呈现警报?

我使用以下警告:

let alertView = UIAlertController(title: "Houps", message: "Could not connect to the server.", preferredStyle: .Alert)
alertView.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
presentViewController(alertView, animated: true, completion: nil)

修改: 代码如下:

if let httpResponse = response as? NSHTTPURLResponse {
                print("HTTP response: \(httpResponse.statusCode)")
                if httpResponse.statusCode == 201 {
                    taskViewController.dismissViewControllerAnimated(true, completion: nil)
                }
            } else {
                print("No HTTP response")
                let alertView = UIAlertController(title: "Houps", message: "Could not connect to the server.", preferredStyle: .Alert)
                alertView.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
                presentViewController(alertView, animated: true, completion: nil)

            }

3 个答案:

答案 0 :(得分:1)

什么对象包含httpResponse定义? presentViewController()调用看起来像是在视图控制器实例上隐式捕获self,当视图响应到达时,视图可能不再位于视图层次结构中。

答案 1 :(得分:0)

你可以试试这个

UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(yourAlertController, animated: true, completion: nil)

用于展示UIAlertController。

答案 2 :(得分:0)

您应该在taskViewController上调用presentViewController:ORKTaskViewController对象

taskViewController.presentViewController(alertView, animated: true, completion: nil)