2

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?

Gui Moura
  • 1,360
  • 1
  • 16
  • 26

1 Answers1

2

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.

Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • I guess you can, but I wouldn't bother unless there was a compelling need. Feels like premature optimization to me... – Rob Oct 19 '14 at 21:42
  • Late comment: My app does regular downloads (user prompted) using a shared `AFHTTPSessionManager` object, and I'd like to add background updates. Should I create another `AFHTTPSessionManager` for this? Or is it possible to change the `NSURLSessionConfiguration` on the fly? – koen Mar 24 '16 at 12:24
  • Yes, you'll need separate `AFHTTPSessionManager` (or `AFURLSessionManager`) for that. You cannot change the [`configuration`](https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/index.html#//apple_ref/occ/instp/NSURLSession/configuration) on the fly. – Rob Mar 24 '16 at 14:59