Tuesday, December 30, 2014

Presenting ViewController from UIAlertView (Attempt to present on which is already presenting )



Presenting ViewController from UIAlertView




Something I face this morning which was annoying ,is That I was trying to present a ViewController
After user Tap on a UIAlertView button.
The result was this console log !!

"uialertview Warning: Attempt to present <_UIModalItemsPresentingViewController: > on <_UIModalItemAppViewController:  > which is already presenting"


The Code I was using looked like this : 


UIAlertView * alert =[[[UIAlertView alloc] initWithTitle:TITLE \
message:MSG \
delegate:Dgt \
cancelButtonTitle:@"OK" \
otherButtonTitles:nil] show];


And in The AlertView Delegate  I called presentViewController


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
     MOImageViewController    *_imageVC =[[UIStoryboard storyboardWithName:@"Main" bundle:nilinstantiateViewControllerWithIdentifier:@"imageScreen"];
                    
                    [_imageVC setImageURLString:urlString];
                    
                     
                    // topViewController  
                    [[self topViewController] presentViewController:_imageVC animated:YES completion:Nil];

}


What turned out is that UIAlertView is treated like viewController and upon clicking at one of its Buttons it gets dismissed, So in the previous code am presenting a new viewController while dismissing the AlertView Which gives me the mentioned warning .

The simplest solution for this is simply using another AlertView Delegate which is 

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
 // presenting view controller here safely


Thats it :)