2014-06-12 85 views
1

我有iOS应用程序,主要功能是上传图片。 我的问题是,有什么情况下应用程序可以继续上传图片和应用程序被解雇时与服务器通信?如何继续在iOS应用程序的后台上传?

感谢

+0

短语“驳回”的意思是_terminated_或去_background_? – holex

+0

@holex去背景。 – user3374800

+0

@ user3374800:我的答案有什么好运? – rdurand

回答

2

如果使用NSURLConnection,你可以使用一个UIBackgroundTaskIdentifier,以保持您的连接活着即使该应用程序发送到后台:

声明你的后台任务标识符,这样你就可以在任何地方访问它的类实现,例如在您.m文件的顶部:

@implementation MyClass { 

    UIBackgroundTaskIdentifier backgroundTaskID; 
} 

创建连接:

NSURLRequest *request = [NSURLRequest requestWithURL: aURL]; 

NSURLConnection *uploadConnection = [NSURLConnection connectionWithRequest:request delegate:self]; 

backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ 

    // Cancel the connection in case of expiration 
    [uploadConnection cancel]; 
}]; 

结束你的后台任务在这两种方法NSURLConnectionDelegate连接结束后/失败:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 

    // Handle a fail 

    [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 

    // Handle a success 

    [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID]; 
} 
+0

我们是否需要为此设置任何UIBackgroundModes? –

+0

不是100%可靠的答案,但我很肯定你不需要。 – rdurand

+0

我也这么认为,但我只是为一个客户做了这个,他说如果他去背景上传仍然失败..反正TNN –

相关问题