在一段时间后显示UIAlertView
我试图显示一段时间后UIAlertView(如在应用程序中做了5分钟后)。 我已经通知用户,如果应用程序closures或在后台。 但是我想在应用程序运行时显示一个UIAlertView。
我试图dispatch_async如下,但警报是永远popup:
[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]; } );
另外,我读了30到60分钟后线头死亡。 我希望能够在超过60分钟后显示警报。
为什么不使用NSTimer
,为什么在这种情况下需要使用GCD?
[NSTimer scheduledTimerWithTimeInterval:5*60 target:self selector:@selector(showAlert:) userInfo:nil repeats:NO];
然后,在同一个class上,你会有这样的事情:
- (void) showAlert:(NSTimer *) timer { UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"title!" message:@"message!" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; [alert show]; [alert release]; }
另外,正如@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];
编辑你现在也可以使用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 });
这是本地通知的创build。 即使您的应用程序背景不亮或者根本没有运行,您也可以设置一个类似UIAlertView的通知,以便在将来再次出现。
这是一个教程。
- 如何包装一个asynchronous方法,它将一个块转换为同步的目标c
- 通过GCD延迟睡眠()
- 我们如何在iOS应用程序转到后台时调度Google Analytics事件?
- 在dispatch_semaphore_dispose上的EXC_BAD_INSTRUCTION(code = EXC_I386_INVOP,子码= 0x0)
- syscall_thread_switch iOS 8.3比赛 – CocoaLumberjack的错误? 如何debugging呢?
- GCD与NSURLConnection
- 核心数据和GCD:将正确的托pipe对象上下文传递给自定义NSManagedObjects
- NSOperationqueue背景,下载图片
- 在应用程序委托中返回之前,等待asynchronous任务完成完成块