Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform task on background thread in iOS, keep execution running even when the application enters background: [closed]

How to perform execution on a background thread? Execution should continue in the background even if the user presses the home button.

like image 551
Rishabh Srivastava Avatar asked Aug 31 '13 09:08

Rishabh Srivastava


1 Answers

Add these properties to your .h file

@property (nonatomic, strong) NSTimer *updateTimer;
@property (nonatomic) UIBackgroundTaskIdentifier backgroundTask;

Now suppose you have a action on button --> btnStartClicked then your method would be like :

-(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
    }
}

and if you need to stop it use this method,

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

    [self.updateTimer invalidate];
    self.updateTimer = nil;
    if (self.backgroundTask != UIBackgroundTaskInvalid)
    {
        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
        self.backgroundTask = UIBackgroundTaskInvalid;
    }
    i = 0;
}
like image 168
Ravi_Parmar Avatar answered Nov 15 '22 05:11

Ravi_Parmar