Appdelegate.h
AppDelegate.m
- (void)applicationDidEnterBackground:(UIApplication *)application { NSLog(@"Application entered background state."); // bgTask is instance variable NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil); bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{ dispatch_async(dispatch_get_main_queue(), ^{ [application endBackgroundTask:self->bgTask]; self->bgTask = UIBackgroundTaskInvalid; }); }]; dispatch_async(dispatch_get_main_queue(), ^{ if ([application backgroundTimeRemaining] > 1.0) { // Start background service synchronously [[BackgroundCleanupService getInstance] run]; } [application endBackgroundTask:self->bgTask]; self->bgTask = UIBackgroundTaskInvalid; }); }
There are several key lines in the above implementation:
First line: bgTask = [application beginBackgroundTaskWithExpirationHandler ..., which requests additional time to run cleanup tasks in the background.
The second is the final code block of the delegate method, starting with dispatch_async. It basically checks if there is time left to complete the operation through a call to [application backgroundTimeRemaining] . In this example, I want to start the background service once, but as an alternative, you can use a loop check on backgroundTimeRemaining at each iteration.
The string [[BackgroundCleanupService getInstance] run] will be the call to our singleton service class, which we will now create.
When the application delegate is ready to launch our background task, now we need a service class that will communicate with the web server. In the following example, I go to a dummy session key and parse the JSON encoded response. In addition, I use two useful libraries to make a request and deserialize the returned JSON, in particular JSONKit and ASIHttpRequest.
BackgroundCleanupService.h
BackgroundCleanupService.m
#import "BackgroundCleanupService.h" #import "JSONKit.h" #import "ASIHTTPRequest.h" @implementation BackgroundCleanupService static BackgroundCleanupService *instance = NULL; +(BackgroundCleanupService *)getInstance { @synchronized(self) { if (instance == NULL) { instance = [[self alloc] init]; } } return instance; } - (void)run { NSURL* URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.example.com/user/%@/endsession", @"SESSIONKEY"]]; __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:URL]; [request setTimeOutSeconds:20];
may I help
source share