用 AFNetworking 配置服务器 Cookie

1,032 阅读1分钟

最近做了一个需求是用Cookie和服务端保持通信会话。

项目的网络框架是 AFNetworking。

原理

  1. 在登录成功的回调函数中,服务器会回显Cookie到RequestHeader中,代码如下:
//获取cookie
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BASE_URL,url]]];
for (NSHTTPCookie *tempCookie in cookies)
{
    //打印cookies
    NSLog(@"getCookie:%@",tempCookie);
    if ([tempCookie.name isEqualToString:@"xxxxxx"/*你需要拿到的cookie的名字*/]) {
        NSDictionary *Request = [NSHTTPCookie requestHeaderFieldsWithCookies:@[tempCookie]];
    }
}   
  1. 保存好获取到的cookie,请求接口的时候加在请求头中。代码如下:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
NSString *cookie = [[NSUserDefaults standardUserDefaults] objectForKey:@"Set-Cookie"];
if (cookie != nil) {
    [request setValue:cookie forHTTPHeaderField:@"Cookie"];
}