Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

ios - How to manage sessions with AFNetworking?

As the title implies, I am using AFNetworking in an iOS project in which the application talks to a server. When the user signs in, the server responds by sending back a success flag and the response headers contain the session ID.

I am wondering if AFNetworking automatically sends the session ID with every subsequent request or should I take care of this myself in some way?

For your information, I have no control over the back-end in terms of how requests are authenticated. I am only building a client that talks to the server.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...