我的要求是更新设置为WKWebView
的Cookie。我可以更新NSHTTPCookieStorage
中的Cookie,但相同的Cookie不会反映到WKWebView
Cookie中(更新值存在于NSHTTPCookieStorage
中,但未设置为{{ 1}})
以下是我用来将cookie设置为AJAX调用的代码。
WKWebView
更新cookie后,我尝试在NSHTTPCookieStorage中打印现有的cookie,显示更新的值。
NSString *strURL = DASHBOARDURL;
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
NSMutableString *script = [[NSMutableString alloc] init];
NSMutableString *cookieString = [[NSMutableString alloc] init];
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
[cookieString appendString:[NSString stringWithFormat:@"%@;", cookie.getCookieString]];
[script appendString:[NSString stringWithFormat:@"document.cookie='%@';",cookie.getCookieString]];
}
[request setValue:cookieString forHTTPHeaderField:@"Cookie"];
//cookies for further AJAX calls
WKUserContentController *userContentController = [[WKUserContentController alloc] init];
WKUserScript *cookieInScript = [[WKUserScript alloc] initWithSource:script
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:NO];
[userContentController removeAllUserScripts];
[userContentController addUserScript:cookieInScript];
WKWebViewConfiguration *webViewConfig = [[WKWebViewConfiguration alloc] init];
webViewConfig.userContentController = userContentController;
CGRect viewRect = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);
wkWebView = [[WKWebView alloc] initWithFrame:viewRect configuration:webViewConfig];
wkWebView.navigationDelegate = self;
[wkWebView loadRequest:request];
[self.view addSubview:wkWebView];
我还尝试在更新Cookie后在NSLog(@"cookies:%@",[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]);
中打印脚本,但它显示旧值。
WKNavigationDelegate
答案 0 :(得分:0)
以下代码解决了我的问题:
NSMutableString *script = [[NSMutableString alloc] init];
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
[script appendString:[NSString stringWithFormat:@"document.cookie='%@';",cookie.getCookieString]];
}
[wkwebView evaluateJavaScript:script completionHandler:^(id test, NSError *error){
NSLog(@"test");
}];
-(NSString *)getCookieString
{
NSString *string = [NSString stringWithFormat:@"%@=%@;expiresDate=%@;path=%@;sessionOnly=%@;isSecure=%@",
self.name,
self.value,
self.expiresDate,
self.path ?: @"/",
self.isSecure ? @"TRUE":@"FALSE",
self.sessionOnly ? @"TRUE":@"FALSE"];
return string;
}