NSURLConnection和beginBackgroundTaskWithExpirationHandler

时间:2014-04-15 07:32:57

标签: ios multithreading ipad background nsurlconnection

我正在使用NSURLConnection下载存档500mb。我想在后台线程上下载它,所以我写道:

NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
self.theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
        self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            // Cancel the connection
            [self.theConnection cancel];
        }];
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskID];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
   [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskID];
}

因此,如果我在主线程上执行此操作,则下载并取消归档并运行良好,但如果我开始下载并按Home按钮,那么它开始在后台线程上工作,它下载70% - 80%并且它已冻结。方法- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error不要致电。

如何在后台线程下载大文件?

编辑1

我发现它叫

self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            [self.theConnection cancel];
        }];

所以连接已完成,但我没有在其他方法中调用endBackgroundTask

1 个答案:

答案 0 :(得分:1)

Apple允许您的应用在后台线程中运行大约10分钟(当您按下主页按钮时)。

您正在寻找NSURLSession:NSURLSession

  

"此API提供了一组丰富的委托方法,用于支持身份验证,并使您的应用能够在您的应用未运行时执行后台下载,或者在iOS中,当您的应用暂停时执行后台下载。"