Search code examples
iosafnetworking-2nsurlsessionbackground-task

AFHTTPSessionManager convenience methods (GET, POST, PUT, etc) and background transfers


I've built an app around AFNetworking 2.0's AFHTTPSessionManager and its nice HTTP convenience methods. I now need to ensure that all of this networking functionality can run in the background, and I'm rather concerned.

Reading Apple's documentation, I can see that data tasks are not supported for background sessions. After looking briefly at AFHTTPSessionManager's implementation of GET, POST, PUT et al, it seems to use NSURLSessionDataTask across the board.

Is there something I'm missing, or do I have some redesign and rework to do?

In the event that I'm right (and I suspect I am), and that this codepath won't allow me to background uploads and downloads, is there any reason I couldn't wrap AFURLSessionManager's other methods that use non-data tasks in the same way the current HTTP methods wrap "dataTaskWithRequest:completionHandler"? For example for a POST I could perhaps use "uploadTaskWithRequest:fromData:progress:completionHandler"?

I'm asking, since I'm wondering if this is a viable route, why the AFNetworking devs didn't use it, so that AFHTTPSessionManager's convenience methods would allow for background transfers.


Solution

  • AFNetworking allows you to perform background requests (though be careful to not use any of the task-specific completion blocks and make sure you implement the appropriate app delegate methods; see AFNetworking 2.0 and background transfers). You probably also can use requestWithMethod of AFHTTPRequestSerializer to simplify the process of building the request, too (though, IIRC, you cannot use HTTPBody of the request with background upload requests, so you might have to save the body of the request to a file and then issue your background upload request using that file).

    But you're absolutely correct that you cannot use the AFHTTPSessionManager methods to initiate NSURLSessionDataTask tasks when using background session. Regarding why they implemented it that way, that's a question better suited for their issues forum.