Search code examples
iosobjective-cios-background-mode

App restart after 180 sec of execution in background mode. By enable the background modes in capabilities


i make a sample app for my requirement the code is given below

design : contain 1 Button 1 Label

enter image description here

.h file code

@interface ViewController : UIViewController{
    int count;
    NSTimer *theTimer;
    UIBackgroundTaskIdentifier counterTask;
}

@property (weak, nonatomic) IBOutlet UILabel *theCount;

.m file code

- (IBAction)start:(id)sender {

    counterTask = [[UIApplication sharedApplication]
                   beginBackgroundTaskWithExpirationHandler:^{
                       // If you're worried about exceeding 10 minutes, handle it here

                       theTimer=[NSTimer scheduledTimerWithTimeInterval:0.1
                                                                 target:self
                                                               selector:@selector(countUp)
                                                               userInfo:nil
                                                                repeats:YES];

                   }];
    count=0;
    theTimer=[NSTimer scheduledTimerWithTimeInterval:0.1
                                              target:self
                                            selector:@selector(countUp)
                                            userInfo:nil
                                             repeats:YES];

}

- (void)countUp {
    if (count==100000) {
        [theTimer invalidate];
        [[UIApplication sharedApplication] endBackgroundTask:counterTask];
    } else {
        count++;
        NSString *currentCount;
        currentCount=[[NSString alloc] initWithFormat:@"%d",count];
        _theCount.text=currentCount;
    }
}

the problem is that when running this app in background (by pressing the home button and minimise the app in iPhone) it relaunch after 180 second even by enabling the background modes in capabilities . i need to extend this up to 4 hours. please help me.


Solution

  • The limit for background tasks is 3 minutes (180 seconds) in later versions of iOS. You cannot extend this to 4 hours.

    Apple Docs:

    Note: Always provide an expiration handler when starting a task, but if you want to know how much time your app has left to run, get the value of the backgroundTimeRemaining property of UIApplication.

    Good Stack Overflow Post on the topic:

    How long does Apple permit a background task to run?