Search code examples
iosobjective-cipadios6

presentViewController causing crash


I'm working on an iPad app using cocos2d, and I'm trying to make it possible to either choose a picture from the library, or take a picture using the camera, to use within the app. I've been googling like mad all day yesterday and today to try and fudge together something to do the above, but I should probably begin by admitting that I don't really know what I'm doing.

The way I have it working right now, you tap the current user image, and it brings up a menu asking if you want to upload a different picture from the camera or the library. Choosing camera calls the following (and the library version is basically the same):

- (void) onGetCameraImage
{
    UIImagePickerController* imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.allowsEditing = NO;

    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [imagePicker presentViewController:[CCDirector sharedDirector] animated:YES completion:NULL];
}

When I try and test this (picking library, of course, since the simulator can't do camera, and yes I do intend to implement the check for no camera), I get the following crash:

2013-04-07 19:21:50.248 prototype1[20897:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present modally an active controller <UIImagePickerController: 0x9e87ac0>.'

I think it's crashing on the presentViewController call, but I'm having a terrible time trying to find out what I'm doing wrong because all of the tutorials and stackoverflow answers use the deprecated modal function call! I suspect I'm just doing all sorts of crazy BS in my previous code? Either way, I have no idea how to get my code to work.

A lot of this code has been gleaned from stack overflow, so I can't guarantee the sensibility of any of it - I'm very new to iOS coding, was basically thrown into this project and we're just trying to make it work. Please help!


Solution

  • Yes something seems wrong here. In order to achieve what you are after when you instantiate the UIImagePickerController you typically want the current view controller to present your image picker instance. The crash is happening becuase:

    1. You are telling the imagepicker to present something from Cocos2D
    2. The UIImagePickerController view is not even on screen yet

    Do you have a access to a view controller?

    If so, you can simply do something like the following:

    [self presentViewController:imagePicker animated:YES completion:nil];
    

    where self is some subclass of UIViewController.

    Hope this helps!