【Objective-C】modalViewが上がるまで処理を待つ方法(同期的に処理する)【Xcode10.2対応】
こういう人に向けて発信しています。
・モーダルやアラートビューなどを同期的に処理したい人
・モーダルが上がった、下がった後に処理したい人
・Objective-C中級者
コード(Objective-C)
#import "ViewController.h"
#import "ModalViewController.h"
@interface ViewController()
@property (assign, nonatomic) BOOL finished;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
-(void)modalShows{
dispatch_async(dispatch_get_main_queue(), ^{
//モーダルをあげる
[self showModal];
//モーダルを下げて、完了時にBOOLをYESに切り替えている。
[self dismissViewControllerAnimated:YES completion:^{
//1回目の上げ下げの後に、2回目の上げ下げ完了後にYESにしている。
[self showModal];
[self dismissViewControllerAnimated:YES completion:^{
self.finished = YES;
}];
}];
});
}
//Button押下時
- (IBAction)buttonTapEvent:(UIButton *)sender {
self.finished = NO;
[self modalShows];
while(!self.finished) {
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}
NSLog(@"モーダルビューを上げて下げた後にログが出力されればOK");
}
-(void)showModal{
ModalViewController *secondVC = [[ModalViewController alloc] init];
[self presentViewController: secondVC animated:YES completion: nil];
}
@end
解説
ボタン押下時のモーダルの動きとしては
1回目:モーダル上がる、下がる
2回目:モーダル上がる、下がるという挙動を実装しています。
上記の書き方であれば、2回目の下がる処理後にログが出されます。