iOS的Cookie管理

背景

最近有一个需求,需要手动的去缓存cookie,然后启动APP的时候设置缓存过的cookie,项目网络框架用的是Afnetworking。

解决方案

翻了下Afnetworking的issue,发现了作者对于cookie的解释

Afnetworking没有对Cookie做过处理

使用NSHTTPCookieStorage即可实现cookie的管理。上代码!

存cookie

1
2
3
4
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:url]];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cookies];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:data forKey:@"cookie"];

设置cookie

1
2
3
4
5
6
7
8
NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:@"m3cookie"];
if([cookiesdata length]) {
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
NSHTTPCookie *cookie;
for (cookie in cookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}

清理cookie

1
2
3
4
5
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies]) {
[storage deleteCookie:cookie];
}

参考文章:

NSHTTPCookieStorage官方文档
Persisting Cookies In An iOS Application?
Clear cookies for response in AFNetworking 2