如何在后台运行NSTimer并在iOS中睡眠?

我在stackoverflow中找到了很多关于NSTimer在后台运行的post。

但是我找不到任何解决方案。

在我的应用程序中,我在后台播放声音,并设置计时器以在达到该时间时停止音乐。

所以我需要运行我的NSTimer背景(意味着当主页按钮单击并睡眠iPhone)。

我怎样才能做到这一点?

 // NSTimer run when app in background 
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil]; loop = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(Update) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:loop forMode:NSRunLoopCommonModes];

这就是你想要的?

你不能

计时器仅存在于您的应用程序中。 所以(除了一个非常小的窗口)当你的应用程序被发送到后台时,计时器不能再开火了。

(音频一直在运行,因为它由系统播放,而不是由您的应用播放。)

所以你不能为此目的使用计时器。

您可以做的事情 – 正如iPatel建议的那样 – 使用本地通知。 这将简要唤醒您的应用程序,让您停止播放音乐。

获取表格[此问题]( http://iphonedevsdk.com/forum/iphone-sdk-development/58643-keep-nstimer-running-when-app-is-in-background-multitasking.html

 - (void)btnSetupNotificationClicked:(id)sender { UILocalNotification* pOrderCompletedNotification=[[UILocalNotification alloc] init]; if(pOrderCompletedNotification!=nil) { [pOrderCompletedNotification setFireDate:[[NSDate alloc] initWithTimeIntervalSinceNow:5.00]]; // [pOrderCompletedNotification setApplicationIconBadgeNumber:1]; [pOrderCompletedNotification setTimeZone:[NSTimeZone systemTimeZone]]; [pOrderCompletedNotification setSoundName:@\"OrderCompleted.m4a\"]; [pOrderCompletedNotification setAlertBody:@\"Order Completed\"]; [pOrderCompletedNotification setAlertAction:nil]; [pOrderCompletedNotification setHasAction:NO]; UIApplication* pApplication=[UIApplication sharedApplication]; if(pApplication!=nil) { [pApplication scheduleLocalNotification:pOrderCompletedNotification]; } else { NSLog(@\"Application singleton allocation error.\"); } [pOrderCompletedNotification release]; [pApplication release]; } else { NSLog(@\"Local notification creation error.\"); } // if } 

随着Swift

 let app = UIApplication.sharedApplication() app.beginBackgroundTaskWithExpirationHandler(nil) let timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector:"DoSomethingFunctions", userInfo: nil, repeats: true) NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes) 

当您运行NSTimer ,@ @selector方法本身将确定您想要在后台或主线程中运行。

初始设置:

 self.scanTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(manageMethod) userInfo:nil repeats:YES]; //@property (nonatomic, strong) NSTimer *scanTimer 

你想在后台运行的情况:

 -(void)manageMethod { dispatch_queue_t queue = dispatch_queue_create("com.mysite.thread1",NULL); dispatch_async(queue,^{ //run in background }); }