To dismiss an alertView is pretty easy, just have to call this method:
- (void)timerExpired{
[alertSOS dismissWithClickedButtonIndex:0 animated:YES];
}
I’m working on a project, and I was wondering how I can dismiss a UIAlertView after like 5 seconds delay without pressing any buttons of the alert. It’s pretty easy. Let me show you how to:
First in the ViewController’s header file (.h) created a timer, and a alertView:
@interface MainViewController : UIViewController{
NSTimer *timer;
UIAlertView *alert;
}
@property (nonatomic, retain) NSTimer *timer;
- (IBAction)buttonPressed:(id)sender;
– (void)timerFired:(NSTimer *)timer;
– (void)timerExpired;
And in the implementation file (.m), I included a buttonPressed action, which will trigger when a specific button is pressed. It will then create a timer, which will call an alertView, and the “timerFired” method every second, which will count back, until it reaches zero, when our AlertView disappears, due to no interaction with it:
#import “MainViewController.h”
@implementation MainViewController
@synthesize timer;
- (IBAction)buttonPressed:(id)sender{
timer = [[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(timerFired:)
userInfo:nil
repeats:YES] retain];
timeCount = 5;
alert = [[UIAlertView alloc] initWithTitle:@”S.O.S”
message:@”Are you in danger? If you don’t press NO in 5 seconds, something will happen.”
delegate:self
cancelButtonTitle:@”NO”
otherButtonTitles:@”YES”, nil];
[alert show];
[alert release];
}
- (void)timerFired:(NSTimer *)timer{
if(timeCount == 0){
[self timerExpired];
} else {
timeCount–;
NSLog(@”timer: %d”, timeCount);
if(timeCount == 0) {
[self timerExpired];
}
}
}
- (void)timerExpired{
[timer invalidate];
[alert dismissWithClickedButtonIndex:0 animated:YES];
}





