iOS|iOS 在WKWebView设置首次携带Cookie、持久化设置Cookie方案、亲测可用

项目中多个地方的WKWebView会影响Cookie缓存,建议测试时一个个来测;

  1. 第一次登录成功后存储Cookie(需要区分ios11系统以后和之前)
+ (void)saveCookies:(WKWebView *)webView handle:(void (^)(BOOL isSuccessful))saveResponse { if (@available(iOS 11.0, *)) { WKHTTPCookieStore *shareCookie = webView.configuration.websiteDataStore.httpCookieStore; [shareCookie getAllCookies:^(NSArray * _Nonnull cookiesArray) { [self dealSaveCookie:cookiesArray handle:saveResponse]; }]; } else { // Fallback on earlier versions NSHTTPCookieStorage * shareCookie = [NSHTTPCookieStorage sharedHTTPCookieStorage]; [self dealSaveCookie:[shareCookie cookies] handle:saveResponse]; }}+ (void)dealSaveCookie:(NSArray *)cookiesArray handle:(void (^)(BOOL isSuccessful))saveResponse { NSMutableArray *TempCookies = [NSMutableArray array]; [TempCookies addObjectsFromArray:cookiesArray]; NSData *cookiesData = https://www.it610.com/article/[NSKeyedArchiver archivedDataWithRootObject:TempCookies]; [[NSUserDefaults standardUserDefaults] setObject:cookiesData forKey:@"webCookie"]; [[NSUserDefaults standardUserDefaults] synchronize]; if (saveResponse) { saveResponse(YES); } }

  1. 在WKWebView的request之前更新Cookie
+ (NSArray *)updateCookies:(WKWebView *)webView { NSMutableArray *localCookies =[NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey: @"webCookie"]]; for (NSHTTPCookie *cookie in localCookies) { if (@available(iOS 11.0, *)) { WKHTTPCookieStore *cookieStore = webView.configuration.websiteDataStore.httpCookieStore; [cookieStore setCookie:cookie completionHandler:nil]; } else { NSHTTPCookieStorage * shareCookie = [NSHTTPCookieStorage sharedHTTPCookieStorage]; [shareCookie setCookie:cookie]; } }return localCookies; }

  1. 在创建WKWebView的时候加入配置实例
- (WKWebView *)webView { if (!_webView) { _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:self.webConfig]; [self.view addSubview:self.webView]; }return _webView; }- (WKWebViewConfiguration *)webConfig { if (!_webConfig) { _webConfig = [[WKWebViewConfiguration alloc] init]; } return _webConfig; }

  1. 在请求的时候处理如下(解决首次携带Cookie)
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.webView.UIDelegate = self; self.webView.navigationDelegate = self; NSString *string = @"/oauth2/v2/authorize?access_type=offline&response_type=code&client_id=100253825&lang=zh-cn&redirect_uri=hms%3A%2F%2Fredirect_url&scope=https%3A%2F%2Fwww.huawei.com%2Fauth%2Faccount%2Fbase.profile+https%3A%2F%2Fsmarthome.com%2Fauth%2Fsmarthome%2Fskill+https%3A%2F%2Fsmarthome.com%2Fauth%2Fsmarthome%2Fdevices&state=state&display=mobile"; NSArray *cookiesArray = [HWCookiesManager updateCookies:self.webView]; NSString *string2 = [NSString stringWithFormat:@"https://login.vmall.com%@",string]; //request首次携带Cookie NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:string2]]; for (NSHTTPCookie *cookie in cookiesArray) { NSDictionary *cookieDict = [cookie dictionaryWithValuesForKeys:@[NSHTTPCookieName, NSHTTPCookieValue, NSHTTPCookieDomain, NSHTTPCookiePath]]; NSString *cookieStr = @""; for (NSString *cookieKey in cookieDict.allKeys) { NSString *keyValue = https://www.it610.com/article/[NSString stringWithFormat:@"%@=%@; ",cookieKey,[cookieDict objectForKey:cookieKey]]; cookieStr = [cookieStr stringByAppendingString:keyValue]; } // cookie 写入request [request addValue:cookieStr forHTTPHeaderField:@"Cookie"]; }// 跨域Cookie注入 NSDictionary *cookieNewDict = [request allHTTPHeaderFields]; NSString *cookieNewStr = [NSString stringWithFormat:@"document.cookie = '%@'; ", [cookieNewDict objectForKey:@"Cookie"]]; WKUserContentController* userContentController = WKUserContentController.new; WKUserScript *cookieInScript = [[WKUserScript alloc] initWithSource:cookieNewStr injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO]; [userContentController addUserScript:cookieInScript]; self.webView.configuration.userContentController = userContentController; // 延迟再次更新Cookie dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ [HWCookiesManager updateCookies:self.webView]; [self.webView loadRequest:request]; }); }

【iOS|iOS 在WKWebView设置首次携带Cookie、持久化设置Cookie方案、亲测可用】源码地址:https://github.com/MacleChen/CFCookieWKWebView.git

    推荐阅读