如何在前台继续在后台继续使用NSURLConnection进行连接?

时间:2012-02-06 16:59:37

标签: ios

我一直在寻找几周的时间来寻找答案,或者是如何做到这一点的一个例子。

NSURLConnection的所有示例/教程都显示它从前台开始或从后台开始,同样是beginBackgrounTaskWithExpirationHandler的所有示例:显示如何在进入后台后启动后台任务。

据我所知,互联网或图书中没有任何内容显示如何在前台开始连接,然后如果没有完成则在后台继续播放。

这个问题的答案实际上并没有回答这个问题:

How should beginbackgroundtaskwithexpirationhandler: be dealt with for an NSUrlConnection that is already in progress?

如果您阅读了引用的Beyond The Basics部分,它会说:"当应用程序处于前台时,后台任务不会产生任何影响"。这意味着如果要在前台下载,则在前台使用NSURLConnection启动后台任务是不可靠的。

1 个答案:

答案 0 :(得分:38)

当您启动下载过程时,只需在您的应用程序位于前台时调用beginBackgroundTaskWithExpirationHandler: 即可。请注意,您必须将返回值存储在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];
}];

这将允许您的应用在下载运行时发送到后台时继续运行。然后,在表示完成下载的委托方法中,您必须放置匹配的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];
}