Under normal circumstances, wkwebView does not need to manually set cookies to initiate a request.
Because there is a common NSHTTHCookieStorage in a process in the iOS system, when sending a request, it will
Pass in the cookie; but we will encounter a situation that requires us to manually write the cookie, directly on the code
1 Splice the cookie parameters that need to be written into js code
//配置config,获取cookieString
- (NSString *)cookieJavaScriptString {
NSMutableString *cookieString = [[NSMutableString alloc] init];
NSDictionary *cookieDic = [mUserDefaults objectForKey:self.cookieCacheName];
for (NSString *key in cookieDic) {
NSHTTPCookie *cookie = [[NSHTTPCookie alloc] initWithProperties:[cookieDic objectForKey:key]];
NSString *excuteJSString = [NSString stringWithFormat:@"document.cookie='%@=%@';", cookie.name, cookie.value];
[cookieString appendString:excuteJSString];
}
for (NSString *key in self.cookieParameter.allKeys) {
NSString *excuteJSString = [NSString stringWithFormat:@"document.cookie='%@=%@';", key, self.cookieParameter[key]];
[cookieString appendString:excuteJSString];
if ([key isEqualToString:@"access_token"]) {
[cookieString replaceOccurrencesOfString:key withString:@"__wyToken" options:NSCaseInsensitiveSearch range:NSMakeRange(0, cookieString.length)];
} else if ([key isEqualToString:@"refresh_token"]) {
[cookieString replaceOccurrencesOfString:key withString:@"__wyRToken" options:NSCaseInsensitiveSearch range:NSMakeRange(0, cookieString.length)];
} else if ([key isEqualToString:@"login_name"]) {
[cookieString replaceOccurrencesOfString:@"login_name" withString:@"__wyUsername" options:NSCaseInsensitiveSearch range:NSMakeRange(0, cookieString.length)];
} else if ([key isEqualToString:@"uid"]) {
[cookieString replaceOccurrencesOfString:@"uid" withString:@"__wyUid" options:NSCaseInsensitiveSearch range:NSMakeRange(0, cookieString.length)];
}
}
//执行js
return cookieString;
}
2 Inject js when initializing webview
WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:[self cookieJavaScriptString] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];
3 After the web page has finished loading, call the cookie-injected js again
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
if (self.cookieParameter.allKeys.count) {
///需要写入cookie
[webView evaluateJavaScript:[self cookieJavaScriptString] completionHandler:^(id result, NSError *error) {
//...
}];
}
。。。。
The above completes the writing of the cookie