2

I need to schedule a task in background when the application enter background state. I have to do this in order to call a remote service each x time and then show a local notification when some event happend with the remote service. (I know it's looks like RPN, yes it is, but for some reason I am not able to use PRM)

I tried this code :

- (void)applicationDidEnterBackground:(UIApplication *)application{

   [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void){
        remoteServiceCallThread = [[NSThread alloc] initWithTarget:self selector:@selector(doRemoteCall:) object:nil];
        [remoteServiceCallThread start];
   }];
}

- (void)applicationWillEnterForeground:(UIApplication *)application{
    [remoteServiceCallThread cancel];   
}

I put breakpoint in the doRemoteCall selector, put is not working.

Maybe my approach is not the best one. If you have any other hack to doing this operation like I describe it I'll take it.

Thank you.

Aladdin Gallas
  • 701
  • 2
  • 12
  • 36

1 Answers1

2

You are not starting the thread, it's initialization code is at the expiration handler block which will be called right before the app is shut down with a timeout:

A handler to be called shortly before the application’s remaining background time reaches 0. You should use this handler to clean up and mark the end of the background task. Failure to end the task explicitly will result in the termination of the application. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified.

The task should be active for 10 minutes only (that is driven by iOS) if your app is not supporting one of the background modes (gps, audio, voip).

You also need to keep the returned UIBackgroundTaskIdentifier reference to be able to mark it as ended if the user brings the app to foreground or when task time is going to the end (that's when the handler block is called).

A-Live
  • 8,904
  • 2
  • 39
  • 74
  • Thank you for the explanation. But this don't tell me how can I design my solution for running background processe when the application is not in foreground. – Aladdin Gallas May 27 '12 at 12:24
  • Place the code after `beginBackgroundTaskWithExpirationHandler`, it well be processed as the app has notified the system it needs to handle the background operations. The `beginBackgroundTaskWithExpirationHandler` might be called at any place, not only at `applicationDidEnterBackground`, this way you can protect your datasource operations from being terminated. – A-Live May 27 '12 at 20:09