博客> iOS的Cookie管理
iOS的Cookie管理
2019-08-24 20:33 评论:0 阅读:540 lvhahaha
ios cookie

使用场景 手动的去除Cookie, 在启动APP的时候设置缓存过的cookie,项目网络框架用的是Afnetworking。

翻了下Afnetworking的issue,发现了作者对于cookie的解释 Afnetworking没有对Cookie做过处理  640.png

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

1.保存cookie

NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:url]];

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cookies];

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

[userDefaults setObject:data forKey:@"cookie"];

2.设置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];
    }

}
  1. 清理cookie

NSHTTPCookie *cookie;

NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];

for (cookie in [storage cookies]) { [storage deleteCookie:cookie]; }

参考文档:https://developer.apple.com/documentation/foundation/nshttpcookiestorage https://www.jianshu.com/p/0d4693357bcb

收藏
2
sina weixin mail 回到顶部