我正在使用 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/