Search code examples
iosobjective-cnsnotificationcenter

Get notifications when UIAlertView is displayed or dismissed, thats shown from another class


I have a UIAlertView that being presented by another class(long story), I want to get notified when the UIAlertView is dismissed in current view.

Similar to this question How to observe when a UIAlertView is displayed?

The accepted answer: Say that class A creates the UIAlert and class B needs to observe it. Class A defines a notification. Class B registers for that notification. When Class A opens the alert it post the notification and class B will see it automatically sounds good,

Has anyone done something similar who could expand on this


Solution

  • You could create your own class MyAlertView that shows the alert normally but posts notifications for events like showing the view and being dismissed.

    Just create a class with a simple interface like -showAlertWithTitle:

    // Class interface
    - (void)showAlertWithTitle:(NSString*)string
    {
        [[UIAlertView alloc] initWithTitle:string message:nil delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil] show];
    }
    
    // UIAlertViewDelegate methods
    - (void)didPresentAlertView:(UIAlertView *)alertView
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"MyAlertViewDidPresentAlert" object:nil];
    }
    
    - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"MyAlertViewDidDismissAlert" object:nil];
    }
    

    Something like that.

    In the first viewController you would need this:

    // First viewController
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didPresentAlert:) name:@"MyAlertViewDidPresentAlert" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didDismissAlert:) name:@"MyAlertViewDidDismissAlert" object:nil];
    }
    
    - (void)didPresentAlert:(NSNotification*)notification
    {...}
    
    - (void)didDismissAlert:(NSNotification*)notification
    {...}