WKWebview传递cookies

1.初始化wk

- (WKWebView *)wkWebView{
if (!_wkWebView) {
 //在初始化过程中即设置cookies
    NSString *cookieStr = [self setCookie];
    WKUserScript *cookieSript = [[WKUserScript alloc]initWithSource:cookieStr injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = NO;
    preferences.javaScriptEnabled = YES;
    //
    WKUserContentController *wkUController = [[WKUserContentController alloc]init];
    [wkUController addUserScript:cookieSript];
    
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc]init];
    wkWebConfig.userContentController = wkUController;
    wkWebConfig.preferences = preferences;
    _wkWebView = [[WKWebView alloc]initWithFrame:FRAME(0, 0, Width, Height - 64) configuration:wkWebConfig];
    _wkWebView.UIDelegate = self;
}
   return _wkWebView;
}

2.设置cookies代码

//初始化WKWebView的设置cookie

- (NSString*)setCookie{

//取cookie
NSData *cookieData = [PublicMethod UserDefaultsWithReadKey:@"Cookie_Data"];
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookieData];
for (NSHTTPCookie *cookie in cookies) {
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}

NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [cookieJar cookies]) {
    [cookieDic setObject:cookie.value forKey:cookie.name];
}

//cookie去重
NSString *cookieStr = @"";
for (NSString *key in cookieDic) {
    
    if ([key isEqualToString:@"JSESSIONID"]) {
        
        NSString *appendString = [NSString stringWithFormat:@"'%@=%@;path=/';",key,[cookieDic valueForKey:key]];
        cookieStr = [NSString stringWithFormat:@"%@document.cookie=%@",cookieStr,appendString];
    }
}
return cookieStr;
}

3.加载网页过程中 再设置cookies

-(void)loadExamplePage:(WKWebView*)webView {

if (_type == 0) {
    _str = VideoListH5;
}else{
    _str = shopList;
}

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_str]];
[request addValue:[PublicMethod UserDefaultsWithReadKey:@"AuthCode"] forHTTPHeaderField:@"AuthCode"];

//写入之前保存的cookies
NSString *cookStr = [self setCookie];
[request setValue:cookStr forHTTPHeaderField:@"Cookie"];
[webView loadRequest:request];
}

你可能感兴趣的:(WKWebview传递cookies)