user3780061
user3780061

Reputation: 65

NSTimer doesn't work in background

I have an issue that my NSTimer doesn't work when the app is working in backgroud. on the simulator it is work, on the device it is not.

my code on the AppDelegate.m:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    NSLog(@"enter background");

    notiTimer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(checkNotification) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:notiTimer forMode:NSDefaultRunLoopMode];
}

and the method I am trying to run in loop:

 -(void)checkNotification {

    NSLog(@"running loop in bg");

    userdetails =[NSUserDefaults standardUserDefaults];
    userid = [userdetails objectForKey:@"userid"];
    username = [userdetails objectForKey:@"username"];
    if (userid != NULL && username != NULL) {

        notifString = [NSString stringWithFormat:@"userid=%@", userid];
        notifData = [NSData dataWithBytes: [notifString UTF8String] length: [notifString length]];
        urlreq = [[NSMutableURLRequest alloc] initWithURL:notifUrl];
        [urlreq setHTTPMethod: @"POST"];
        [urlreq setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
        [urlreq setHTTPBody: notifData];
        sendreq = [NSURLConnection sendSynchronousRequest:urlreq returningResponse:nil error:nil];
        response =[[NSString alloc] initWithBytes:[sendreq bytes] length:[sendreq length] encoding:NSUTF8StringEncoding];
        responsTrimmed = [response stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        splitResponse = [responsTrimmed componentsSeparatedByString: @","];
        if ([splitResponse[0] isEqualToString:@"1"]) {
            NSLog(@"%@",splitResponse[1]);
        }
        else {
            NSLog(@"err");
        }
    }

}

now once at the app enter to background I get at the debugger the NSLog:

  NSLog(@"enter background");

but the run loop doesn't work and the method doesn't call in loop and I don't get NSLog

NSLog(@"running loop in bg");

on the debugger, any idea ?

Upvotes: 0

Views: 792

Answers (1)

Marco Pace
Marco Pace

Reputation: 3870

When your application goes in background, it is "frozen" by the OS, so no task can be executed in the normal way. The application itself should declare how it handles background task, but you are limited to one of this situation:

  • you need a little amount of time (usually less then 10 minute): you can simply ask for it
  • your app is downloading something: you can ask the system to continue the download for you
  • a little set of task can be executed in background, but you have to specify it in your project

So in order to execute some code, you have to start a background task at quit time.

Here is the Apple documentation for Background Execution, hope it can help you.

Upvotes: 5

Related Questions