如何在前台继续在后台继续使用NSURLConnection进行连接? [英] How can a connection started with NSURLConnection while in the foreground be continued in the background?

查看:190
本文介绍了如何在前台继续在后台继续使用NSURLConnection进行连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been searching for literally weeks to try to find an answer, or an example of how to do this.

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

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:

应该如何处理已经在进行的NSUrlConnection?

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

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.

推荐答案

你只需调用 beginBackgroundTaskWithExpirationHandler: while 当您开始下载过程时,您的应用程序就在前台。请注意,您必须将返回值存储在ivar / property中:

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

这将允许您的应用在下载运行时发送到后台时继续运行。然后,在表示下载完成的委托方法中,您必须放置匹配的 endBackgroundTask:

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

这篇关于如何在前台继续在后台继续使用NSURLConnection进行连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆