2012-02-06 106 views
18

我一直在寻找几个星期来尝试找到答案或如何做到这一点的例子。如何在后台继续在前台继续使用NSURLConnection开始连接?

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

据我所知,在互联网或书籍上没有任何东西显示如何在前景中开始连接,然后如果未完成则在后台继续。

回答这个问题实际上并没有回答这个问题:如果你看过referened超越基础部分,它说

How should beginbackgroundtaskwithexpirationhandler: be dealt with for an NSUrlConnection that is already in progress?

:“虽然应用程序是在前台,后台任务赢得”没有任何效果“。这意味着如果你想在前台下载,在前台使用NSURLConnection来启动后台任务是不可能的。

+0

文件称“虽然应用程序是在前台,后台任务将不会有任何影响;但,如果用户将应用程序移动到后台,后台任务的存在将自动保持应用程序运行,以便它可以完成操作。“这对我来说非常有意义,因为后台任务应该如何工作 - 一旦您在前台开始任务(例如下载文件),如果应用程序进入后台,它将完成下载任务,而不会减少网络连接。 – sbs 2013-02-26 20:43:33

回答

38

您只需拨打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]; 
} 
+0

只是试过这种方法,就像NSURLConnection的魅力一样!谢谢! – sbs 2013-02-26 21:29:04

+0

请注意,现在这种方法在iOS 7以后只能在后台运行3分钟,有没有办法让它活着? – CGR 2017-01-11 22:30:33

相关问题