I have been searching for literally weeks to try to find an answer, or an example of how to do this.
All the examples/tutorials for NSURLConnection show it starting in the foreground or starting in the background, ditto all the examples for beginBackgrounTaskWithExpirationHandler: show how to start a background task after entering the background.
As far as I can tell there is nothing out there on the internet or books that shows how to start a connection while in the foreground and then if its not finished continue it in the background.
The answer to this question does not actually answer the question:
How should beginbackgroundtaskwithexpirationhandler: be dealt with for an NSUrlConnection that is already in progress?
If you read the referened Beyond The Basics section it says: "While the app is in the foreground the background task won't have any effect". This means it is not possisble to start a background task using NSURLConnection while in the foreground if you want to download in the foreground.
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With