Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

ios - How can a connection started with NSURLConnection while in the foreground be continued in the background?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...