1

我正在使用下面提到的方法在 a 中设置 cookie WKWebview我可以将 cookie 设置为由 WKWebView 使用吗?

但是我设置的 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

  1. WKWebViewcookie设置回NSHTTPCookieStorage 运行时(在AJAX调用期间)
  2. 我可以使用任何委托方法控制 AJAX 调用 cookie 吗?

以下是我的getCookieStringcategory( 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;
}
4

2 回答 2

1

如果 cookie 存储中有多个 cookie 的域(或路径)与请求的 URL 匹配,则会发送多个 cookie。

在编写getCookieString方法时,您可能已经更改或添加domain=了字符串的一部分。这将导致第二个有效 cookie 被存储并随您的请求一起发送。

于 2016-06-26T21:35:15.563 回答
0

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;
}
于 2016-06-27T09:23:17.827 回答