calling unwind segue from camera method fails

2019-08-13 16:50发布

问题:

My unwind segue code is working fine. I use storyboard to wire things up. And when I run the app, all is well.

But in addition to clicking a button, I want to also do the unwinding from code. Basically I am presenting a modal that contains two buttons: Camera, Gallery. User clicks on one of the buttons to go to either get an image from the camera or from the gallery. So once the image is obtained, I no longer need the modal view. Hence, as the last step in the method (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info, I call my unwind segue as

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
  //... do work here and then
  [self performSegueWithIdentifier:@"myUnwindName" sender:self];
}

But when I do I get the following error

attempt to dismiss modal view controller whose view does not currently appear. 
self = <UITabBarController: 0x127d09b80> modalViewController = <UIImagePickerController: 0x127e2fd80>

I understand the problem. But I don't know how to fix it.

Basically I am not supposed to make the call "while" the camera view is still on screen (i.e. my modal is not on screen yet). But then where do I make the call? Is there such a thing as ImagePickerDidClose or something akin to it? I couldn't find one. So thanks for any help.

回答1:

When the imagePickerController:didFinishPicking... method fires, this is your opportunity to dismiss the image picker controller as such:

[picker dismissViewControllerAnimated:YES completion:nil];

In most cases, when we call this line of code, we're sending nil for the completion argument. However, if we want to do something when this dismissal is complete (as we do here), we pass a completion block argument:

[picker dismissViewControllerAnimated:YES completion: ^{
    [self performSegueWithIdentifier:@"myUnwindName" sender:self];
}];