問題点
今更ながらUIAlertViewがdeprecatedになった警告に対応しました。
'UIAlertView' is deprecated: first deprecated in iOS 9.0 - UIAlertView is deprecated.
という警告ですね。
どう変えればいいかはググればいっぱい出てくるので割愛しますが、問題点は・・・
- 表示対象のUIViewControllerが必要。
- 二つのUIViewControllerを一つのUIViewController常に
presentViewController
できない。
という問題です。
例えば、どこかのUIViewController内で表示してるのであれば、
UIAlertController *alert = [UIAlertController alertControllerWithTitle: title
message: message
preferredStyle: UIAlertControllerStyleAlert];
UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK"
style: UIAlertActionStyleDefault
handler: handler];
[alert addAction: ok];
[self presentViewController:alert animated:YES completion:nil];
といった感じで表示できますが、昔のUIAlertViewはどこからでも表示できたので、例えばModelの中などでも使用されてたり、UIViewControllerが取得できないdelegateの中で使用されてたりして困りました。
そこでAPPからrootControllerを取得してそこに表示すればええやん!ってことでやってみました。
UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
[rootController presentViewController:alert animated:YES completion:nil];
こういう感じですね。これで表示はされるのですが、同じくUIPopoverControllerも同じpresentViewController:alert
を使って表示される仕組みに変わっていて、それがrootController
に表示された状態同じようにアラートを出そうとすると
Warning: Attempt to present <UIAlertController ....> ... which is already presenting
のような警告がでて無視されちゃうんですね。Modelの中で色々使いまわされてるので、どんなシチュエーションでも必ず表示されるアラートが欲しい!というわけで色々試した結果いけそうなのができたので共有します。
解決策
UIAlertController *alert = [UIAlertController alertControllerWithTitle: title
message: message
preferredStyle: UIAlertControllerStyleAlert];
UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK"
style: UIAlertActionStyleDefault
handler: nil];
[alert addAction: ok];
UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
if(rootController.presentedViewController != nil){
[rootController.presentedViewController presentViewController:alert animated:YES completion:nil];
} else {
[rootController presentViewController:alert animated:YES completion:nil];
}
まあ、単純な話ですが、既にpresentedViewControllerがあったらそこに表示、なければrootに表示するだけです。
みんな大好きStackOverFlowで見つけました。サイトはSwiftのコードですね。