WKWebView对Cookie的处理

WKWebView对Cookie的处理

 

因为WKWebView是通过WebKit内核进行网络处理的,所以我们的NSHTTPCookieStorage里的Cookie是没办法拿到并带进一个请求的。可以通过下面的方法手动添加:

 
  1. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];

  2. NSArray *cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies;

  3. NSDictionary *requestHeaderFields = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];

  4. //设置请求头

  5. request.allHTTPHeaderFields = requestHeaderFields;

  6. 复制代码

这种方式只对单个请求有效,一旦URL改变,Cookie还是会丢失,所以我们可以通过WKWebView的代理

  • (void)webView: decidePolicyForNavigationAction: decisionHandler: 来对每一个request进行Cookie处理
 
  1. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

  2. [[WKCookieManager shareManager] fixNewRequestCookieWithRequest:navigationAction.request];

  3. decisionHandler(WKNavigationActionPolicyAllow);

  4. }

  5.  
  6. - (NSURLRequest *)fixNewRequestCookieWithRequest:(NSURLRequest *)originalRequest{

  7. NSMutableURLRequest *fixedRequest;

  8. if ([originalRequest isKindOfClass:[NSMutableURLRequest class]]) {

  9. fixedRequest = (NSMutableURLRequest *)originalRequest;

  10. } else {

  11. fixedRequest = originalRequest.mutableCopy;

  12. }

  13. //防止Cookie丢失

  14. NSDictionary *dict = [NSHTTPCookie requestHeaderFieldsWithCookies:[NSHTTPCookieStorage sharedHTTPCookieStorage].cookies];

  15. if (dict.count) {

  16. NSMutableDictionary *mDict = originalRequest.allHTTPHeaderFields.mutableCopy;

  17. [mDict setValuesForKeysWithDictionary:dict];

  18. fixedRequest.allHTTPHeaderFields = mDict;

  19. }

  20. return fixedRequest;

  21. }

  22. 复制代码

#####另外一种方式: 可以在WKWebViewConfiguration的userContentController中注入脚本:

 
  1. WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];

  2. WKUserContentController *controller = [[WKUserContentController alloc] init];

  3. [controller addUserScript:[[WKCookieManager shareManager] futhureCookieScript]];

  4. configuration.userContentController = controller;

  5.  
  6. - (WKUserScript *)futhureCookieScript{

  7. // source 就是我们要调用的 JS 函数或者我们要执行的 JS 代码

  8. // injectionTime 这个参数我们需要指定一个时间,在什么时候把我们在这段 JS 注入到 WebVeiw 中,它是一个枚举值,WKUserScriptInjectionTimeAtDocumentStart 或者 WKUserScriptInjectionTimeAtDocumentEnd

  9. // MainFrameOnly 因为在 JS 中,一个页面可能有多个 frame,这个参数指定我们的 JS 代码是否只在 mainFrame 中生效

  10. - initWithSource:injectionTime:forMainFrameOnly:

  11. WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:[self cookieString] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];

  12. return cookieScript;

  13. }

  14.  
  15. - (NSString *)cookieString

  16. {

  17. NSMutableString *script = [NSMutableString string];

  18. [script appendString:@"var cookieNames = document.cookie.split('; ').map(function(cookie) { return cookie.split('=')[0] } );\n"];

  19. for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {

  20.  
  21. if ([cookie.value rangeOfString:@"'"].location != NSNotFound) {

  22. continue;

  23. }

  24.  
  25. NSString *string = [NSString stringWithFormat:@"%@=%@;domain=%@;path=%@",

  26. cookie.name,

  27. cookie.value,

  28. cookie.domain,

  29. cookie.path ?: @"/"];

  30.  
  31. if (cookie.secure) {

  32. string = [string stringByAppendingString:@";secure=true"];

  33. }

  34.  
  35. [script appendFormat:@"if (cookieNames.indexOf('%@') == -1) { document.cookie='%@'; };\n", cookie.name, string];

  36. }

  37. return script;

  38. }

  39. 复制代码

####iOS11之后 iOS11之后,有一个更简便的方法:

 
  1. /*! @abstract Returns the cookie store representing HTTP cookies in this website data store. */

  2. @property (nonatomic, readonly) WKHTTPCookieStore *httpCookieStore API_AVAILABLE(macosx(10.13), ios(11.0));

  3.  
  4. //发送请求前插入cookie;

  5. NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];

  6. WKHTTPCookieStore *cookieStore = [WKWebsiteDataStore defaultDataStore].httpCookieStore;

  7.  
  8. if (cookies.count > 0) {

  9. for (NSHTTPCookie *cookie in cookies) {

  10. [cookieStore setCookie:cookie completionHandler:^{

  11.  
  12. }];

  13. }

  14. }

  15.  
  16. 复制代码

转载于:https://juejin.im/post/5d22f3525188251bb869f1c3

你可能感兴趣的:(IOS,ios,objective-c)