我正在尝试与UIWebView共享WKWebView Cookie以获取所有cookie。我知道从UIWebView获取所有cookie非常简单,因为比较WKWebView。
我在选项卡式应用程序模板中创建两个WebView(WKWebView,UIWebView(。我正在使用以下方法与UIWebView共享WKWebViewcookie,但没有成功。
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
let response = navigationResponse.response as? HTTPURLResponse
let cookies = HTTPCookie.cookies(withResponseHeaderFields: response?.allHeaderFields as! [String : String], for: (response?.url)!)
HTTPCookieStorage.shared.cookieAcceptPolicy = HTTPCookie.AcceptPolicy.always
for cookie in cookies {
HTTPCookieStorage.shared.setCookie(cookie)
}
decisionHandler(WKNavigationResponsePolicy.allow);
}
当我从WKWebView登录我的帐户时,使用上面的代码,UiWebView还没有登录我。我还尝试与WKWebView共享UIWebView Cookie,它奏效了。
请谁能告诉我如何与UIWebView共享WKWebView Cookie,或者我如何从WKWebView获取所有cookie?
谢谢
您需要按照以下步骤设置 wkwebview cookie
初始化中的第一个是执行脚本来设置 Cookie:
-(void)initWebView
{
WKWebViewConfiguration *webViewconfiguration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
if(URL.host hasSuffix:baseDomain){
//Here to determine whether the domain name is their own website
NSString *jScript = [self setCookies];
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[wkUController addUserScript:wkUScript];
}
webViewconfiguration.userContentController = wkUController;
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, width, height) configuration:webViewconfiguration];
}
//The script that executes may be slightly different
+(NSString *)setCookies
{
NSString *script = [NSString string];
for (NSHTTPCookie *httpCookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
{
NSString *cookie = [NSString stringWithFormat:@"%@=%@;domain=%@;path=%@",httpCookie.name,httpCookie.value,httpCookie.domain,httpCookie.path?:@"/"];
script = [script stringByAppendingString:[NSString stringWithFormat:@"document.cookie='%@';",cookie]];
}
return script;
}
然后在创建 NSURLRequest 对象时手动将 cookie 添加到 HTTP 的标头中:
- (void)loadRequest:(NSURLRequest *)request
{
//Here to determine whether the domain name is their own website
if ([request.URL.host hasSuffix:baseDomain]){
NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:request.URL];
NSString *cookies = @""; //setting Cookies
[mutableRequest addValue:cookies forHTTPHeaderField:@"Cookie"];
}
// do request
}
视图真的很痛苦,在加载网络视图之前设置 cookie 很棘手。 如果仅使用委托方法设置 Cookie,则永远不会首次加载页面。 您必须在加载页面之前处理好cookie。 你可以在其他问题中回答我的答案,但它是 swift 的,但你可以在目标 C 中遵循相同的技术。我可以设置由WKWebView使用的cookie吗?