如何在后台继续在前台继续使用NSURLConnection开始连接?
问题描述:
我一直在寻找几个星期来尝试找到答案或如何做到这一点的例子。如何在后台继续在前台继续使用NSURLConnection开始连接?
NSURLConnection的所有示例/教程都显示它在前台开始或从后台开始,与beginBackgrounTaskWithExpirationHandler的所有示例一样:显示如何在进入后台后启动后台任务。
据我所知,在互联网或书籍上没有任何东西显示如何在前景中开始连接,然后如果未完成则在后台继续。
回答这个问题实际上并没有回答这个问题:如果你看过referened超越基础部分,它说
:“虽然应用程序是在前台,后台任务赢得”没有任何效果“。这意味着如果你想在前台下载,在前台使用NSURLConnection来启动后台任务是不可能的。
答
您只需拨打beginBackgroundTaskWithExpirationHandler:
而当您开始下载过程时,您的应用程序在前台右侧。请注意,您必须返回值存储在伊娃/属性:
@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];
}
文件称“虽然应用程序是在前台,后台任务将不会有任何影响;但,如果用户将应用程序移动到后台,后台任务的存在将自动保持应用程序运行,以便它可以完成操作。“这对我来说非常有意义,因为后台任务应该如何工作 - 一旦您在前台开始任务(例如下载文件),如果应用程序进入后台,它将完成下载任务,而不会减少网络连接。 – sbs 2013-02-26 20:43:33