如何使用 AFNetworking 管理会话? [英] How to manage sessions with AFNetworking?

查看:46
本文介绍了如何使用 AFNetworking 管理会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所暗示的,我在一个应用程序与服务器通信的 iOS 项目中使用 AFNetworking.当用户登录时,服务器通过发送成功标志作为响应,响应头包含会话 ID.

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.

我想知道 AFNetworking 是否会在每个后续请求中自动发送会话 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.

推荐答案

是的,您的会话 ID 应该在您登录后自动发送,只要 cookie 在发送下一个请求之前没有过期(重要细节确定).AFNetworking 使用的 NSURLConnection 会为您处理这些细节.

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.

在后端 AFNetworking 使用 NSURLConnection,它依次自动更新 NSHTTPCookieStorage 以存储会话.您可以通过处理 cookie 存储来随意操作或删除 cookie.

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.

就像如果您想在服务中显示为未登录,您可以删除与该域关联的会话 cookie.如果您已经登录并尝试再次登录,我使用过的某些服务会出错.此外,无法检查登录状态.快速修复,从 URL 获取 cookie 并删除它们:

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];
}

来自开发者本人

这篇关于如何使用 AFNetworking 管理会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆