You simply call beginBackgroundTaskWithExpirationHandler:
while your app is in the foreground right when you start the download process. Note that you have to store the return value in an ivar/property:
@property (nonatomic, assign) UIBackgroundTaskIdentifier backgroundTaskID;
@synthesize backgroundTaskID;
...
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
self.backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
// Cancel the connection
[connection cancel];
}];
This will allow your app to keep running if it gets sent to the background while the download is running. Then, in your delegate methods that signify the completion of the download, you have to place the matching 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];
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…