我正在使用下面提到的方法在WKWebview:Can I set the cookies to be used by a WKWebView?中设置cookie
但是,我设置的cookie是在AJAX调用中复制的。我是说他们被重复了两次。
下面是我使用的代码片段:
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]) {
[script appendString:[NSString stringWithFormat:@"document.cookie='%@';",cookie.getCookieString]];
[cookieString appendString:[NSString stringWithFormat:@"%@;", 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:YES];
[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];getCookieString是一种将cookie值作为NSString返回的方法。
WKWebView会在运行时(在AJAX调用期间)将cookie设置为NSHTTPCookieStorage吗?下面是我的getCookieString分类(NSHTTPCookie (CookieObject))方法
- (NSString *)getCookieString {
NSString *string = [NSString stringWithFormat:@"%@=%@;domain=%@;expiresDate=%@;path=%@;sessionOnly=%@;isSecure=%@",
self.name,
self.value,
self.domain,
self.expiresDate,
self.path ?: @"/",
self.isSecure ? @"TRUE":@"FALSE",
self.sessionOnly ? @"TRUE":@"FALSE"];
return string;
}发布于 2016-06-26 21:35:15
如果cookie存储中有多个cookie,其域(或路径)与请求的URL匹配,则会发送多个Cookies。
在编写getCookieString方法时,您可能已经更改或添加了字符串的domain=部分。这将导致存储第二个有效的cookie,并将其与请求一起发送。
发布于 2016-06-27 09:23:17
从我的domain=方法中删除getCookieString修复了这个问题
-(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;
}https://stackoverflow.com/questions/37856891
复制相似问题