How to run NSTimer in background and sleep in iOS?

一曲冷凌霜 提交于 2019-12-03 11:17:14

问题


I found a lot of post in stackoverflow about NSTimer run in background.

However I didn't find any solution.

In my app , I play sound in background and I set timer to stop music when it reached that time.

So I need to run my NSTimer background (mean when home button click and sleep iPhone).

How can I do that?


回答1:


// 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?.




回答2:


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.




回答3:


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
}



回答4:


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)



回答5:


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
      });
}


来源:https://stackoverflow.com/questions/15092016/how-to-run-nstimer-in-background-and-sleep-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!