将AFNetworking 2.0与后台任务一起使用 [英] Using AFNetworking 2.0 with background tasks
问题描述
我在使用AFURLSessionManager实施后台任务时遇到问题。
我正在使用 NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:
并使用便捷方法创建POST请求,使用BaseURL和SessionConfiguration创建一个新的AFHTTPSessionManager。
I'm having issues implementing background tasks using AFURLSessionManager.
I'm creating a new AFHTTPSessionManager with BaseURL and SessionConfiguration, using NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:
and using the convenience method to create a POST request.
运行我的应用程序时,第一个请求正常发送,但第二个返回标识符为{ID}的后台URLSession已经存在!
When I run my app, the first request is sent normally, but the second one returns A background URLSession with identifier {ID} already exists!
and it crashes the app.
我看过Apple的WWDC 2013视频,他们建议您只使用一次创建会话配置,
I've watched Apple's WWDC 2013 videos and they suggest you to create the Session Configuration only once, by using
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.yourcompany.appId.BackgroundSession"];
session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
});
但是设置了AFURLSessionManager的 session
属性作为只读,没有办法让我传递自定义的NSURLSession,只有一个NSURLSessionConfiguration,它是在 AFURLSessionManager:init
:
However there session
property for AFURLSessionManager is set as readonly and there is no way for me to pass a custom NSURLSession, only a NSURLSessionConfiguration, that is created inside AFURLSessionManager:init
:
self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue];
我觉得我做错了什么,但是我还能使用AFNetworking支持后台任务吗?
I feel like I'm doing something wrong, but how else can I support background tasks using AFNetworking?
推荐答案
您无法实例化新的 AFHTTPSessionManager
是正确的更改其会话
以引用某些单例 NSURLSession
。因此,相反,您应该使 AFHTTPSessionManager
对象本身成为可以在整个应用程序中重复使用的共享实例。
It is correct that you cannot instantiate a new AFHTTPSessionManager
and then change its session
to reference some singleton NSURLSession
. So, instead, you should make the AFHTTPSessionManager
object, itself, the shared instance which you can reuse throughout the app.
在此答案的结尾,我提供了一个使用AFNetworking进行后台会话的示例。
At the end of this answer, I provide an example of using AFNetworking for background sessions.
这篇关于将AFNetworking 2.0与后台任务一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!