【发布时间】:2016-06-16 10:42:50
【问题描述】:
我正在使用下面提到的方法在 WKWebview 中设置 cookie:
Can I set the cookies to be used by a WKWebView?
但是我设置的 cookie 在 AJAX 调用中被复制了。我的意思是它们被重复了两次。
这是我使用的代码sn-p:
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是否会将 cookie 设置回NSHTTPCookieStorage在运行时(在 AJAX 调用期间) - 我可以使用任何委托方法控制 AJAX 调用 cookie 吗?
以下是我的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;
}
【问题讨论】:
-
请注意,“sessionOnly”和“isSecure”在参数列表中的顺序错误。
-
在处理键值对时,顺序真的很重要吗?无论如何,我会在这里尝试并发表评论..
-
实际上,确实如此,因为您没有使用键值对。您正在连接一个字符串。因此 sessionOnly=%@;isSecure=%@ 在这种情况下应该读作 sessionOnly= + self.isSecure + ;isSecure= + self.sessionOnly
标签: ios objective-c wkwebview wkwebviewconfiguration