在項目中遇到一個情況在VC1中有一個當(dāng)網(wǎng)絡(luò)連接斷開后會彈框(UIAlertView)提醒用戶網(wǎng)絡(luò)斷開,在iOS8以上使用的時UIAlertController,如果當(dāng)前屏幕窗口顯示的控制器是VC1通過present出來的VC2就會出現(xiàn)Warning: Attempt to present xxx on xxx whose view is not in the window hierarchy!
原因就是使用UIAlertController也是present的出來的,當(dāng)VC1同時present兩個控制器就會在控制臺打印這種錯誤,并且不會彈出來提醒框。
解決方法:
1、在網(wǎng)絡(luò)斷開執(zhí)行的方法把當(dāng)前present的控制器干掉,提醒框才能彈出來
UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (topController.presentedViewController) {
topController = topController.presentedViewController;
[topController dismissViewControllerAnimated:NO completion:nil];
}
}
2、獲取當(dāng)前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];
詳見這里