Skip to content

Instantly share code, notes, and snippets.

@akashgupta88
Last active November 1, 2015 19:07
Show Gist options
  • Save akashgupta88/87c00e0d9cdb68ea7447 to your computer and use it in GitHub Desktop.
Save akashgupta88/87c00e0d9cdb68ea7447 to your computer and use it in GitHub Desktop.
A simple category which adds a familiar method (UIAlertView) for showing a UIAlertController instance from anywhere in your iOS project.
#import <UIKit/UIKit.h>
@interface UIAlertController (Show)
-(void)show;
-(void)showWithCompletion:(void(^)())completion;
-(void)showWithCompletion:(void(^)())completion failure:(void(^)())failure;
@end
#import "UIAlertController+Show.h"
@implementation UIAlertController (Show)
-(void)show
{
[self showWithCompletion:nil];
}
-(void)showWithCompletion:(void(^)())completion
{
[self showWithCompletion:completion failure:nil];
}
-(void)showWithCompletion:(void(^)())completion failure:(void(^)())failure
{
UIViewController *viewController = [self topMostViewController];
if (viewController)
{
[viewController presentViewController:self animated:YES completion:completion];
}
else
{
if (failure)
{
failure();
}
else
{
NSLog(@"ERROR: Could not find a viewController to present from!");
}
}
}
#pragma mark - Internal
-(UIViewController*)topMostViewController
{
UIViewController *viewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
if (viewController)
{
while (viewController.presentedViewController)
{
viewController = viewController.presentedViewController;
}
}
if (viewController.isBeingDismissed || viewController.isBeingPresented || viewController.isMovingFromParentViewController || viewController.isMovingToParentViewController)
{
return nil;
}
return viewController;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment