IOS WKWebView添加cookie

在网络请求中,有一部分需要添加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的信息我封装了一下:

#pragmamark - 拼接cookie- (NSString*)readCurrentCookieWith:(NSDictionary*)dic{

    if(dic == nil) {

        return nil;

    }else{

        NSHTTPCookieStorage*cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

        NSMutableString *cookieString = [[NSMutableString alloc] init];

        for(NSHTTPCookie*cookiein [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];  [cookiePropertiessetObject:@"cookie_user"forKey:NSHTTPCookieName];  [cookiePropertiessetObject:uidforKey:NSHTTPCookieValue];  [cookiePropertiessetObject:@"xxx.xxx.com"forKey:NSHTTPCookieDomain];[cookiePropertiessetObject:@"/"forKey:NSHTTPCookiePath];  [cookiePropertiessetObject:@"0"forKey:NSHTTPCookieVersion]; [cookiePropertiessetObject:[[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 (cookiein cookieAry) { 

        [cookieJar deleteCookie: cookie]; 

    } 

}

附上原博主链接原文

你可能感兴趣的:(IOS WKWebView添加cookie)