I have a use case that should be rather common but I can’t find an easy way to handle it with AFNetworking:
Whenever the server returns a specific status code for any request, I want to:
- remove a cached authentication token
- re-authenticate (which is a separate request)
- repeat the failed request.
I thought that this could be done via some global completion/error handler in AFHTTPClient, but I didn’t find anything useful. So, what’s the “right” way to do what I want? Override enqueueHTTPRequestOperation: in my AFHTTPClient subclass, copy the operation and wrap the original completion handler with a block that does what I want (re-authenticate, enqueue copied operation)? Or am I on the wrong track altogether?
Thanks!
EDIT: Removed reference to 401 status code, since that’s probably reserved for HTTP basic while I’m using token auth.
In the AFHTTPClient’s init method register for the
AFNetworkingOperationDidFinishNotificationwhich will be posted after a request finishes.In the notification handler check the status code and
copytheAFHTTPRequestOperationor create a new one.EDIT:
In general you should not need to do that and just handle the authentication with this AFNetworking method: