How to manage sessions with AFNetworking? How to manage sessions with AFNetworking? ios ios

How to manage sessions with AFNetworking?


Yes, your session ID should be sent automatically once you are logged in, as long as the cookie does not expire before the next request is sent (important detail to be sure of). NSURLConnection, which AFNetworking uses, takes care of the details for this for you.

On the backend AFNetworking is using NSURLConnection which in turn automatically updates NSHTTPCookieStorage to store the session. You can manipulate or delete the cookies as you see fit by messing with the cookie storage.

Like if you wanted to appear to the service as not logged in, you could just delete the session cookie associated to that domain. Some services I have worked with will error if you are already logged in and attempt to login again. Additionally there was no way to check login status. Quick fix, get the cookies from URL and delete them :

NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL: networkServerAddress];for (NSHTTPCookie *cookie in cookies) {    [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];}

From the developer himself


This depends on the specification given by the service you are interacting with. I have worked with similar services and they have explicitly stated in their documentation that, In order to maintain the session valid I must poll the service at every few seconds by sending int "1".

However, If possible could please post the service name or any reference which we can read. If it is any company's private API then they must have described the use of the session id which they are returning.


Underlying technologies will take care of it, However if you want to persist those cookies then this answer for other question.

Persisting Cookies In An iOS Application?