在项目中遇到一个情况在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];
详见这里