---
title: "how to use beginBackgroundTaskWithExpirationHandler"
author: "zani"
date: "2013-12-21T16:05:58Z"
tags: []
categories: ["移动开发"]
slug: "how-to-use-beginbackgroundtaskwithexpirationhandler"
draft: false
lastmod: "2013-12-21T16:05:58Z"
id: 1993313
url: "https://zani.iteye.com/blog/1993313"
---

```
- (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;
}
```