Search code examples
objective-ciosuiimagepickercontrolleruitabbar

Making a UIViewController a UIImagePicker when tapped


I have an app that uses the UITabBarController and one of the tabs is supposed to be a full on camera view (similar to Instagram). When I launch the app and go to that view, most of the screen is blank and no image library picker/camera view loads. Any help would be greatly appreciated.

Here is my viewDidLoad method:

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

    imagePicker = [[UIImagePickerController alloc] init];

    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
    } else {
        [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    }

    [imagePicker setDelegate:self];

    [imagePicker setEditing:NO];

    // Place image picker (camera viewing angle on the screen)
    [self presentViewController:imagePicker animated:YES completion:nil];
}

Solution

  • Try putting that code in viewDidAppear instead -- that worked for me. Better yet, would be to put all but the last line in viewDidLoad, so it's only called once, and just put the last line in the viewDidAppear method. When you cancel the image picker (the only thing I tested), it will just reappear, since viewDidAppear will be called again, so you need to implement imagePickerControllerDidCancel: like this to keep that from happening:

    - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
        [self dismissViewControllerAnimated:YES completion:nil];
        self.imagePicker = nil;
    }
    

    And, in your viewDidAppear, put in an if statement to see if the picker exists before trying to present it:

    if (self.imagePicker) {
        [self presentViewController:self.imagePicker animated:YES completion:nil];
        }