LoginSignup
0
1

More than 3 years have passed since last update.

UIAlertViewのようにいつでもどこでも必ず表示されるアラートを実現

Posted at

問題点

今更ながら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のコードですね。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1