Search code examples
iosxcodebackgroundnstimerclose-application

NSTimer and closing app while in background


I've encountered problem with closing the app while in background. When working in the background, tapping 2x and swiping the app to close it, the app doesn't call the applicationWillTerminate:(UIApplication *)application, but goes to @autoreleasespool, which is definitely crash.

I suppose it is connected with working NSTimer, because without initializing it the app closes properly from background.

I wanted to disable the NSTimer in the appDelegate with no success, since NSTimer can be disabled only from the same thread.

I am starting NSTtimer in init of my class:

[NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(checkLastSeenTimeofPeripheral) userInfo:nil repeats:YES];

I wanted to stop it while going to background using the answer given here, but still it doesn't seem to stop the timer and the app crashes on termination.

EDIT:

Initializing in myClass

- (id)init {
    self = [super init];

    if(self){
        //check the connection timer
        [self startCheckLastSeenTimeOfPeripheralTimer];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopCheckLastSeenTimeOfPeripheralTimer) name:UIApplicationDidEnterBackgroundNotification object:[UIApplication sharedApplication]];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startCheckLastSeenTimeOfPeripheralTimer) name:UIApplicationWillEnterForegroundNotification object:[UIApplication sharedApplication]];

methods to start/stop timer

-(void)startCheckLastSeenTimeOfPeripheralTimer {
    _checkLastSeenTimeOfPeripheralTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f
                                                                           target:self
                                                                         selector:@selector(checkLastSeenTimeofPeripheral)
                                                                         userInfo:nil
                                                                          repeats:YES];
    NSLog(@"checkLastSeenTimeofPeripheralTimer started");
}

-(void)stopCheckLastSeenTimeOfPeripheralTimer {
    if (_checkLastSeenTimeOfPeripheralTimer) {
        [_checkLastSeenTimeOfPeripheralTimer invalidate];
        _checkLastSeenTimeOfPeripheralTimer = nil;
        NSLog(@"checkLastSeenTimeofPeripheralTimer stopped");
    }
    else {
        NSLog(@"checkLastSeenTimeofPeripheralTimer not initialized - can't stop");
    }
}

Solution

  • According to documentation appWillTerminate is not being called when closing suspended App: Suspended apps receive no notification when they are terminated; the system kills the process and reclaims the corresponding memory. Apps get suspended by the system while in background without informing about it.