保持 NSTimer 在后台运行

Yos*_*han 0 objective-c nstimer

我有以下代码,每次用户单击特定按钮时都会运行 1 分钟。

timer = [[NSTimer alloc]init];
        timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果应用程序处于后台模式,如何保持其运行,以便计时器仍然继续工作?

提前致谢!

小智 5

//NSTimer run in background.

NSTimer *myTimer;  <br>  
 [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];<br>
   myTimer = [NSTimer scheduledTimerWithTimeInterval:60.0
                                 target:self
                               selector:@selector(targetMethod:)
                               userInfo:nil
                                repeats:YES];<br>
[[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSRunLoopCommonModes];
Run Code Online (Sandbox Code Playgroud)