dismiss a modalviewcontroller when the application

2019-05-14 08:13发布

i need to dismiss my uiimagepicker modal viewcontroller automatically when the application enters the background.i tried to put the code to dismissmodalviewcontroller code in viewdiddissappear method,but its not being called.so i made a reference to the viewcontroller in appdelegate and tried to put it in the applicationdidenterbackgroundmethod but still it is not working.can someone point out the right way to do this

3条回答
Luminary・发光体
2楼-- · 2019-05-14 09:05

I don't think you need to go through all that.

From the docs:

If you present several modal view controllers in succession, and thus build a stack of modal view controllers, calling this method on a view controller lower in the stack dismisses its immediate child view controller and all view controllers above that child on the stack.

Try calling [self dismissModalViewController:NO] from the parent view controller in your implementation of - (void) viewDidUnload.

This is untested, but the docs imply that it should do the job for you.

查看更多
甜甜的少女心
3楼-- · 2019-05-14 09:07

Best way to remove the modal when app is moving to background and it works fine .

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(dismissView:)
                                                 name:UIApplicationDidEnterBackgroundNotification object:nil];
} 

- (void)dismissView:(id)sender {
     [self dismissModalViewControllerAnimated:YES];
}

- (void)dealloc {

     [[NSNotificationCenter defaultCenter] removeObserver:self];
}

Also you can remove observer like this

 [[NSNotificationCenter defaultCenter] removeObserver: self
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:nil];
查看更多
可以哭但决不认输i
4楼-- · 2019-05-14 09:08

Try to add an NSNotificationCenter observer for UIApplicationDidEnterBackgroundNotification in the UIViewController that you want to dismiss. Use the selector to dismiss the modalview

- (void)viewWillAppear:(BOOL)animated
{
   [[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector(didEnterBackground:) 
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
   [[NSNotificationCenter defaultCenter] removeObserver: self
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:nil];
}

- (void)didEnterBackground:(NSNotification*)note
{
  [self.navigationController dismissModalViewAnimated:NO];
}
查看更多
登录 后发表回答