views:

1584

answers:

3

Hi all,

I'm trying to show a UIImagePickerController as soon as one of my view controller loads. I'd like to this without the user having to press a button so I overrode the viewDidLoad method as follows:

- (void)viewDidLoad {
    [super viewDidLoad];

    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.allowsImageEditing = YES;
    imagePickerController.delegate = self;    
    [self presentModalViewController:imagePickerController animated:YES];
    [imagePickerController release];
}

This compiles and runs, however when the view controller is loaded the image picker is not displayed. This code works fine if I attach it to an event of a button for example. Any ideas?

Thanks.

A: 

It seems that viewDidLoad is too early to use presentModalViewController:animated:. I'd sugget to fork off a one-shot timer to call the method from next run loop iteration:

[NSTimer
 scheduledTimerWithTimeInterval:0
 target:self
 selector:@selector(onLoadTimer:)
 userInfo:nil
 repeats:NO];

add the following method:

- (void)onLoadTimer:(id)unused
{
    [self presentModalViewController:imagePickerController animated:YES];
    [imagePickerController release];
}
Farcaller
Thanks for the reply but this doesn't seem to work. The program hangs on: [self presentModalViewController:imagePickerController animated:YES];
aloo
There could be many seconds or even minutes in between when the view is created and when it would have access to the UI itself (typically when it is added as a subview to something else or added into a nav/tab controller.
Kevlar
+1  A: 

Try putting the code in

-(void)viewDidAppear

That even runs every time the view appears on the screen though (including when it appears after you dismiss the UIImagePicker), so you might have to add a BOOL value to make it only happen the first time it shows, or when you want it (i.e. not after dismissing a modal view).

kiyoshi
This. If a view controller doesn't have any access to the displayed UI somehow, it can't interact with it in the way you want, i think.
Kevlar
+3  A: 

I had the same problem but solved it. Try using

-(void) awakeFromNib {

}

It will load just after everything else loads.

and it will load only once, which could be what you expect, or not
hhafez
Thanks for this, great tip!
optician