[英]Displaying UIAlertView after some time
I'm trying to display a UIAlertView after some time (like 5 minutes after doing something in the app). 我想在一段时间后显示一个UIAlertView(比如在应用程序中做一些事情后的5分钟)。 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.
但我希望在应用程序运行时显示UIAlertView。
I tried to dispatch_async as follows but the alert is popping forever: 我尝试dispatch_async如下,但警报永远弹出:
[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. 另外,我读到线程在30到60分钟后死亡。 I want to be able to display the alert after more than 60 min.
我想能够在超过60分钟后显示警报。
Why not use an NSTimer
, why would you need to use GCD in this case? 为什么不使用
NSTimer
,为什么在这种情况下你需要使用GCD?
[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: 另外,正如@PeyloW所说,你可以使用
performSelector:withObject:afterDelay:
:
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: 编辑你现在也可以使用GCD的
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.
您可以设置类似UIAlertView的通知,以便将来某个时间出现,即使您的应用程序是后台运行或根本不运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.