iOS 中UIWebView的cookie
Posted 村里竹竿2016
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS 中UIWebView的cookie相关的知识,希望对你有一定的参考价值。
有关cookie是什么,大家可以自行百度,本文我获得cookie的目的是得到一个userID。
下面的是代码。
- (void)getUserIDFromCookie { NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; NSArray *cookies = [sharedHTTPCookieStorage cookiesForURL:urlStr]; NSEnumerator *enumerator = [cookies objectEnumerator]; NSHTTPCookie *cookie; while (cookie = [enumerator nextObject]) { NSLog(@"%@,%@", [cookie name], [cookie value]); } }
由此得到的cookie,大家可以根据cookie里面的内容进行遍历,来得到自己想要的值。
对于ios 来说 NSHTTPCookieStorage 会存储APP自身访问所有url的cookie,可以用domain为标志来获取自己所需要的cookie。需要注意的是,NSHTTPCookieStorage存储的cookie在过期后会自动删除,如用户手动调整时间超过期时间则系统也会自动删除,因此某些业务逻辑需要注意。
设置cookie:
- (void)setCookie{ NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary]; // 设置 cookie 的参数 [cookieProperties setObject:@"cookie_user" forKey:NSHTTPCookieName]; [cookieProperties setObject:uid forKey:NSHTTPCookieValue]; [cookieProperties setObject:@"xxx.xxx.com" forKey:NSHTTPCookieDomain]; [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath]; [cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion]; [cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires]; NSHTTPCookie *cookieuser = [NSHTTPCookie cookieProperties]; [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser]; }
接下来说下清除所有cookie:
NSHTTPCookie *cookie; NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; for (cookie in [storage cookies])
{
[sharedHTTPCookieStorage deleteCookie:cookie];
}
// 缓存 清除
[[NSURLCache sharedURLCache] removeAllCachedResponses];
清除某个url下的cookie:
- (void)deleteCookie{ NSHTTPCookie *cookie; NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; NSArray *cookieAry = [sharedHTTPCookieStorage cookiesForURL: [NSURL URLWithString:urlStr]];
for (cookie in cookieAry)
{
[sharedHTTPCookieStorage deleteCookie: cookie];
}
}
参考文章:在UIWebView中设置cookie
以上是关于iOS 中UIWebView的cookie的主要内容,如果未能解决你的问题,请参考以下文章
iOS 和 H5 页面交互(WKWebview 和 UIWebview cookie 设置)
iOS 如何为每个 UIWebView 请求添加 cookie?