In my app I need to show a UIImagePickerController when a button is tapped. Here is the code I used in the method called by the button on the controller when it gets pressed:
- (IBAction)choosePressed:(id)sender {
if (!self.pickerController) self.pickerController = [[UIImagePickerController alloc]init];
self.pickerController.delegate = self;
self.pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self.navigationController presentViewController:self.pickerController animated:YES completion:nil];
}
Problem is that UIImagePickerControllers are very slow to load, so I thought that moving the initialization of the picker in the viewDidAppear:animated method, possibly in another thread, would have been a good way to fasten the process of creation/showing of the picker so I did this:
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
dispatch_queue_t myQueue = dispatch_queue_create("Picker Queue", NULL);
dispatch_async(myQueue, ^{
self.pickerController = [[UIImagePickerController alloc]init];
self.pickerController.delegate = self;
});
}
- (IBAction)choosePressed:(id)sender {
self.pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self.navigationController presentViewController:self.pickerController animated:YES completion:nil];
}
With this the pickerController shows up immediately when the button is pressed but when the main controller is loaded the UI freezes for a little bit (probably because of the initializzation of the pickerController) but the init should be done in another thread since I used the dispatch_async mechanism shouldn’t it? Is there any mistake in my code?
I’m very new to GCD so I must be missing something!
It’s a misuse of UIKit to access it from a background thread. You could perhaps show a “loading…” screen briefly. I think the best policy is to not worry about it.