How to run NSTimer in background and sleep in iOS?

爱⌒轻易说出口 提交于 2019-12-03 00:47:29
vualoaithu
// NSTimer run when app in background <br>

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

This is what do you want?.

You can’t

Timers only exist within your application. So (except for a very small window) when your app is sent to the background, timers cannot fire anymore.

(The audio keeps running, because it’s played by the system, and not by your app.)

So you cannot use timers for this purpose.

What you can do — as suggested by iPatel — is use a local notification, instead. This will briefly awake your app, allowing you to stop playing the music.

Get Form [This Question] (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
}

With 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)

When you run NSTimer, the @selector method itself will determine wether you want to run in background or main thread.

Initial set up:

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

Case you want to run in Background:

-(void)manageMethod
{
      dispatch_queue_t queue = dispatch_queue_create("com.mysite.thread1",NULL);
      dispatch_async(queue,^{ 
           //run in background
      });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!