![img_76445a8e971be8d410081a72f82f71d9.jpe](https://i-blog.csdnimg.cn/blog_migrate/4c88748ab420ecaddc110aa146c77096.jpeg)
photo-1490633874781-1c63cc424610.jpeg
背景
最近有一个需求,需要手动的去缓存cookie,然后启动APP的时候设置缓存过的cookie,项目网络框架用的是Afnetworking。
解决方案
翻了下Afnetworking的issue,发现了作者对于cookie的解释
Afnetworking没有对Cookie做过处理
![img_41662705812fd30c0dedf774c1b3ccfa.jpe](https://i-blog.csdnimg.cn/blog_migrate/d0572299525fcd4d955bf88616119d41.jpeg)
15197156684835.jpg
使用NSHTTPCookieStorage
即可实现cookie的管理。上代码!
存cookie
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:url]];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cookies];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:data forKey:@"cookie"];
设置cookie
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
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