Using AFNetworking 2.0 with background tasks

試著忘記壹切 提交于 2019-12-24 04:38:08

问题


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.

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.

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];
});

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];

I feel like I'm doing something wrong, but how else can I support background tasks using AFNetworking?


回答1:


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.

At the end of this answer, I provide an example of using AFNetworking for background sessions.



来源:https://stackoverflow.com/questions/26453822/using-afnetworking-2-0-with-background-tasks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!