Displaying UIAlertView after some time

前端 未结 2 448
半阙折子戏
半阙折子戏 2021-01-07 05:54

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

相关标签:
2条回答
  • 2021-01-07 06:31

    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
    });
    
    0 讨论(0)
  • 2021-01-07 06:31

    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 讨论(0)
提交回复
热议问题