爱编程

iOS开发-WKWebView设置cookie

2018-08-31  本文已影响2118人  来者可追文过饰非

1.初始化WKWebView时设置cookie

#pragma mark - lazy

- (WKWebView *)webView {
    if (!_webView) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        // 偏好设置
        config.preferences = [[WKPreferences alloc] init];
        config.preferences.minimumFontSize = 10;
        config.preferences.javaScriptEnabled = YES;
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        
        // 设置cookie
        config.processPool = [[WKProcessPool alloc] init];
        NSDictionary *dic = '你的cookie数据';
        // 将所有cookie以document.cookie = 'key=value';形式进行拼接
        NSMutableString *cookie = @"".mutableCopy;
        
        if (dic) {
            for (NSString *key in dic.allKeys) {
                [cookie appendFormat:@"document.cookie = '%@=%@';\n",key,dic[key]];
            }
        }
        
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:cookie injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
        [userContentController addUserScript:cookieScript];
        
        config.userContentController = userContentController;
        config.selectionGranularity = WKSelectionGranularityDynamic;
        config.allowsInlineMediaPlayback = YES;
        config.mediaPlaybackRequiresUserAction = false;
        
        CGRect frame = 'webview的frame';
        _webView = [[WKWebView alloc] initWithFrame:frame configuration:config];
    }
    return _webView;
}

2.WKWebView已经存在时,设置cookie

- (void)setcookie {
    
    if (!_webView) {
        return;
    }
    NSDictionary *dic = '你的cookie数据';
    NSSLog(@"%@",dic);
    // 将所有cookie以document.cookie = 'key=value';形式进行拼接
    NSMutableString *cookie = @"".mutableCopy;
    for (NSString *key in dic.allKeys) {
        [cookie appendFormat:@"document.cookie = '%@=%@';\n",key,dic[key]];
    }
    self.cookie = cookie.copy;
    NSString *cookieValue = cookie;
    [_webView evaluateJavaScript:cookieValue completionHandler:^(id result, NSError *error) {
        NSSLog(@"cookie-------%@",result);
    }];
}
上一篇下一篇

猜你喜欢

热点阅读