ios - NSURLConnection 和 beginBackgroundTaskWithExpirationHandler

标签 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

最佳答案

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

NSURLSession 就是你要找的:NSURLSession

"This API provides a rich set of delegate methods for supporting authentication and gives your app the ability to perform background downloads when your app is not running or, in iOS, while your app is suspended."

关于ios - NSURLConnection 和 beginBackgroundTaskWithExpirationHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23077267/

相关文章:

ios - 没有 DispatchQueue.main.async 的意外布局行为

ios - iOS App评论-我可以放置演示功能吗?

ios - 如何动态设置tableview单元格高度?

iphone - 在多个 UIWebViews 中不记得网站登录

c - 如何在多线程矩阵乘法中使用线程池和消息队列?

multithreading - 连通分量的并行算法

ios - 无法在 iPad 上录制 : Error Domain=NSOSStatusErrorDomain Code=1718449215 "(null)"

iPad Safari 忽略 html5 视频上方的 div onclick

使用 iPhone SDK beta 5 提交 iPad 应用程序被拒绝

ios - 如何在滚动到整页的地方实现 collectionview 的干净分页