在iOS中的后台线程上执行任务,即使应用程序进入后台,也要继续执行:

Ris*_*ava 5 background-process ios

如何在后台线程上执行?即使用户按下主页按钮,执行也应在后台继续.

Rav*_*mar 8

将这些属性添加到.h文件中

@property (nonatomic, strong) NSTimer *updateTimer;
@property (nonatomic) UIBackgroundTaskIdentifier backgroundTask;
Run Code Online (Sandbox Code Playgroud)

现在假设您对按钮 - > btnStartClicked有一个操作,那么您的方法将是:

-(IBAction)btnStartClicked:(UIButton *)sender {
    self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.5
                                                        target:self
                                                      selector:@selector(calculateNextNumber)
                                                      userInfo:nil
                                                       repeats:YES];
    self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        NSLog(@"Background handler called. Not running background tasks anymore.");
        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
        self.backgroundTask = UIBackgroundTaskInvalid;
    }];

}

 -(void)calculateNextNumber{
    @autoreleasepool {
      // this will be executed no matter app is in foreground or background
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你需要停止使用这个方法,

- (IBAction)btnStopClicked:(UIButton *)sender {

    [self.updateTimer invalidate];
    self.updateTimer = nil;
    if (self.backgroundTask != UIBackgroundTaskInvalid)
    {
        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
        self.backgroundTask = UIBackgroundTaskInvalid;
    }
    i = 0;
}
Run Code Online (Sandbox Code Playgroud)