Add these properties to your .h file
@property (nonatomic, strong) NSTimer *updateTimer; @property (nonatomic) UIBackgroundTaskIdentifier backgroundTask;
Now suppose you have an action on a button β btnStartClicked then your method will look like this:
-(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 {
and if you need to stop 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; }
source share