UIAlertController_whose view is not in the window hierarchy!问题

今天在学习UIAlertController的过程中,出现了一个警告,且没有弹出警告框,警告信息如下:

Paste_Image.png
1.UIAlertController
  • 到了iOS 9.0之后,UIAlertViewUIActionSheet都被弃用了,取而代之的就是用UIAlertController封装了UIAlertViewUIActionSheet这两个控件的。实际上,UIAlertController在iOS 8.0以后就可以使用了。
  • UIAlertController是继承自UIViewController的,所以使用
    presentViewController:animated:completaion:方法来显示UIAlertController
解决方法1:

通过GCD在开启一个线程,使用了dispatch_async是将block发送到指定线程去执行,当前线程不会等待,会继续向下执行,在另外一个线程中处理这些操作,然后通知主线程更新界面。

    override func viewDidLoad() {
        super.viewDidLoad()
        let alertController = UIAlertController(title: "保存或删除数据", message: "删除数据将不可恢复",preferredStyle: .ActionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: .Cancel, handler: nil)
        let deleteAction = UIAlertAction(title: "删除", style: .Destructive, handler: nil)
        let archiveAction = UIAlertAction(title: "保存", style: .Default, handler: nil)
        alertController.addAction(cancelAction)
        alertController.addAction(deleteAction)
        alertController.addAction(archiveAction)
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
             //在另外一个线程中处理这些操作,然后通知主线程更新界面。
            dispatch_async(dispatch_get_main_queue(), { 
                 self.presentViewController(alertController, animated: true, completion: nil)
            })
        }
    }
解决方法2:

将此代码放到viewDidApper方法中

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        let alertController = UIAlertController(title: "保存或删除数据", message: "删除数据将不可恢复",preferredStyle: .ActionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: .Cancel, handler: nil)
        let deleteAction = UIAlertAction(title: "删除", style: .Destructive, handler: nil)
        let archiveAction = UIAlertAction(title: "保存", style: .Default, handler: nil)
        alertController.addAction(cancelAction)
        alertController.addAction(deleteAction)
        alertController.addAction(archiveAction)
        self.presentViewController(alertController, animated: true, completion: nil)
    }

你可能感兴趣的:(UIAlertController_whose view is not in the window hierarchy!问题)