在网络请求中,有一部分需要添加cookie,接下来就把为web添加cookie的方法小小列举一下,其实所有的要添加cookie的网络请求包括web,最终都是要在request上添加,如下:
if (_webView == nil) { // 1)创建WebView _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, Kwidth, Kheight-64)]; // 2)设置代理 _webView.delegate = self; _webView.scalesPageToFit = YES; _webView.scrollView.bounces = NO; } // 3)设置URL地址 NSURL *url = [NSURL URLWithString:strUrl]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; NSDictionary *cookie = [AppInfo shareAppInfo].userModel.cookies; if (cookie != nil) { [request addValue:[self readCurrentCookieWith:cookie] forHTTPHeaderField:@"Cookie"]; }else{ [request addValue:@"" forHTTPHeaderField:@"Cookie"]; } [_webView loadRequest:request]; [self.view addSubview:_webView];
其中获得cookie的信息我封装了一下:
#pragma mark - 拼接cookie - (NSString*)readCurrentCookieWith:(NSDictionary*)dic{ if (dic == nil) { return nil; }else{ NSHTTPCookieStorage*cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage]; NSMutableString *cookieString = [[NSMutableString alloc] init]; for (NSHTTPCookie*cookie in [cookieJar cookies]) { [cookieString appendFormat:@"%@=%@;",cookie.name,cookie.value]; } //删除最后一个“;” [cookieString deleteCharactersInRange:NSMakeRange(cookieString.length - 1, 1)]; return cookieString; } }
[self setCookie];//设置cookie
在此之前,设置cookie。
//设置cookie
- (void)setCookie{
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[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]; }
NSHTTPCookieStorage
实现管理共享的cookie存储一个singleton对象(共享实例)。 这些cookies是所有的应用程序之间的共享和跨进程同步保存
//清除cookie
- (void)deleteCookie{
NSHTTPCookie *cookie;
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookieAry = [cookieJar cookiesForURL: [NSURL URLWithString: _urlstr]]; for (cookie in cookieAry) { [cookieJar deleteCookie: cookie]; } }