Wednesday, May 22, 2013

endBackgroundTask example UIApplication ios


[UIApplication endBackgroundTask]

Marks the end of a specific long-running background task.
- (void)endBackgroundTask:(UIBackgroundTaskIdentifier)identifier
Parameters
identifier
An identifier returned by the beginBackgroundTaskWithExpirationHandler:method.
Discussion of [UIApplication endBackgroundTask]
You must call this method to end a task that was started using thebeginBackgroundTaskWithExpirationHandler: method. If you do not, the system may kill your application.
This method can be safely called on a non-main thread.
Example of [UIApplication endBackgroundTask]
if ([[UIDevice currentDevice] isMultitaskingSupported]) {
    [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];
    backgroundTaskID = UIBackgroundTaskInvalid;
}
Example of [UIApplication endBackgroundTask]
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // Handle the error
    ...

    [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskID];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // Save the downloaded data
    ...

    [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskID];
}
Example of [UIApplication endBackgroundTask]
- (void) doUpdate

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        [self beginBackgroundUpdateTask];

        NSURLResponse * response = nil;
        NSError  * error = nil;
        NSData * responseData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];

        // Do something with the result

        [self endBackgroundUpdateTask];
    });
}
- (void) beginBackgroundUpdateTask
{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}

- (void) endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}