Warning: Attempt to present xxx on xxx whose view is not in the window hierarchy!

在項目中遇到一個情況在VC1中有一個當網絡連接斷開后會彈框(UIAlertView)提醒用戶網絡斷開,在iOS8以上使用的時UIAlertController,如果當前屏幕窗口顯示的控制器是VC1通過present出來的VC2就會出現Warning: Attempt to present xxx on xxx whose view is not in the window hierarchy!
原因就是使用UIAlertController也是present的出來的,當VC1同時present兩個控制器就會在控制臺打印這種錯誤,并且不會彈出來提醒框。
解決方法:
1、在網絡斷開執行的方法把當前present的控制器干掉,提醒框才能彈出來

        UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
        while (topController.presentedViewController) {
            topController = topController.presentedViewController;
                [topController dismissViewControllerAnimated:NO           completion:nil];
            }
        }

2、獲取當前present的控制器再進行彈框

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"..." message:@"+++" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"ssss" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:action];
    
    UIViewController *topVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    [topVC presentViewController:alertController animated:YES completion:nil];

詳見這里

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容