Skip to content

Instantly share code, notes, and snippets.

@nubbel
Last active December 16, 2015 05:09
Show Gist options
  • Save nubbel/5382154 to your computer and use it in GitHub Desktop.
Save nubbel/5382154 to your computer and use it in GitHub Desktop.
//
// ViewController.m
// DetectAlertView
//
// Created by Dominique d'Argent on 4/14/13.
// Copyright (c) 2013 Dominique d'Argent. All rights reserved.
//
#import "ViewController.h"
@implementation ViewController
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:spinner];
[spinner startAnimating];
// Show alert view in 2 seconds
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[[[UIAlertView alloc] initWithTitle:@"Alert"
message:@"Message"
delegate:nil
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil] show];
});
[[NSNotificationCenter defaultCenter] addObserverForName:UIWindowDidBecomeKeyNotification
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
UIWindow *window = [note object];
for (UIView *view in window.subviews) {
if ([view isKindOfClass:[UIAlertView class]]) {
NSLog(@"ALERT!!!");
[spinner stopAnimating];
}
}
}];
}
@end
@maxsz
Copy link

maxsz commented Apr 15, 2013

Although this looks very promising, it does not work in my scenario (both the dispatch_async and UINotification approach). This is probably because of how the alert is displayed in my case (it's a system alert). There is no UIAlertView in the view hirarchy of any window. This works for me:

__block id alertObserver;
alertObserver = [[NSNotificationCenter defaultCenter]
    addObserverForName:UIApplicationWillResignActiveNotification
    object:nil
    queue:[NSOperationQueue mainQueue]
    usingBlock:^(NSNotification *note) {
        [spinner stopAnimating];
        [[NSNotificationCenter defaultCenter] removeObserver:alertObserver];
    }
];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment