Search code examples
xcodeios7

how to auto dismiss UIAlertView when app becomes active


OK, I have an app that runs a timer. If the user is watching the app's timer count down (e.g. the app is awake and active in the foreground) I want an alert to be shown to the user. I've added this code to my timer when it reaches 0:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Reminder" message:@"It's time!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];

The problem I'm having is that if I put the phone to sleep or make the app inactive in some other fashion I have a local notification setup to handle this alerting so when the user goes back to the app I don't want them to see the alert mentioned above. It's an unnecessary "click" they have to make.

Is there a way to auto dismiss this alert when the app either goes into the background or enters the foreground if it's been triggered?


Solution

  • You have to use NSNotificationcenter at the UIAlertview definition.

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
    
    [alert show];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillResignActiveNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification* notification){
        [alert dismissWithClickedButtonIndex:0 animated:NO];
    }];