Gui Moura
Gui Moura

Reputation: 1360

Using AFNetworking 2.0 with background tasks

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?

Upvotes: 2

Views: 5240

Answers (1)

Rob
Rob

Reputation: 437381

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.

Upvotes: 2

Related Questions