开发者

Displaying UIAlertView after some time

I'm trying to display a UIAlertView after some time (like 5 minutes after doing something in the app). I'm already notifying the user if the app is closed or in background. But I want to display a UIAlertView while the app is running.

I tried to dispatch_async as follows but the alert is popping forever:

[NSThread sleepForTimeInterval:minutes];
 dispatch_async(dispatch_get_main_queue(),
       ^{
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"title!" message:@"message!" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
        [alert show];
        [alert release];
       }
       );

Also, I read that the thread dies after 30 to 60 minutes. I want to be able开发者_开发百科 to display the alert after more than 60 min.


Why not use an NSTimer, why would you need to use GCD in this case?

[NSTimer scheduledTimerWithTimeInterval:5*60 target:self selector:@selector(showAlert:) userInfo:nil repeats:NO];

Then, within the same class, you'd have something like this:

- (void) showAlert:(NSTimer *) timer {
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"title!" 
                                                     message:@"message!" 
                                                    delegate:self               
                                           cancelButtonTitle:@"Cancel"
                                           otherButtonTitles:nil];
    [alert show];
    [alert release];
}

Also, as @PeyloW noted, you can use performSelector:withObject:afterDelay: too:

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"title!" 
                                                 message:@"message!" 
                                                delegate:self               
                                       cancelButtonTitle:@"Cancel"
                                       otherButtonTitles:nil];
[alert performSelector:@selector(show) withObject:nil afterDelay:5*60];
[alert release];

EDIT You can now also use GCD's dispatch_after API:

double delayInSeconds = 5;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"title!"
                                                        message:@"message"
                                                       delegate:self
                                              cancelButtonTitle:@"Cancel"
                                              otherButtonTitles:nil];
    [alertView show];
    [alertView release]; //Obviously you should not call this if you're using ARC
});


This is the kind of thing that Local Notifications were created for. You can set an UIAlertView-like notification to come up some time in the future, even if your app is backgrounded or not running at all.

Here is a tutorial.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜