尝试在视图不在 window 层次结构中的 <ViewController:> 上显示 <UIAlertController: >

Attempt to present <UIAlertController: > on <ViewController:> whose view is not in the window hierarchy

我正在使用 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)

我收到以下错误:

尝试呈现 UIAlertController:... ViewController:...其视图不在 window 层次结构中

知道如何在关闭 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)

            }

你可以试试这个

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

用于呈现 UIAlertController。

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

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

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