项目需要对`WKWebView`进行Cookie同步,在网上找了好多方法,经过测试:
第一种(无效):通过`evaluateJavaScript`注入,这种方法是注入不了Cookie的,因为js没有权限
第二种(无效):通过请求头的方法,`[request setValue:@"cookie string" forHTTPHeaderField:@"Cookie"]`,这种方法js不能通过document.cookie获取到cookie
第二种:通过`addUserScript`方法,如果你的WKWebView已经登录了,只需要在`WKWebView`的初始化的时候注入一次就好了,但是如果你的`WKWebView`是要在页面上动态同步`Cookie`的话,还需要其它操作,下面是我的解决方案。
初始化WKWebView注入Cookie
- (instancetype)initWithFrame:(CGRect)frame configuration:(nonnull WKWebViewConfiguration *)configuration
{
//一定要在[super initWithFrame:frame configuration:configuration]之前设置,否则无效
WKUserContentController *userContentController = WKUserContentController.new;
WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:[self updateCookies] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];
configuration.userContentController = userContentController;
self = [super initWithFrame:frame configuration:configuration];
if (self) {
self.scrollView.bounces = NO;
self.scrollView.showsHorizontalScrollIndicator = NO;
[self sizeToFit];
self.backgroundColor = HSQColorGray250;
self.allowsBackForwardNavigationGestures = YES;
[self addSubview:self.progressView];
[self addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial context:nil];
}
return self;
}
这里拼接是Cookie
- (NSString *)updateCookies
{
NSMutableString *cookieValue = [NSMutableString stringWithFormat:@""];
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//这边是在登录接口保存了登录Cookie
NSString *loginCookie = [[NSUserDefaults standardUserDefaults] objectForKey:kDMUserLoginCookie];
NSMutableString *mHsqCookie = [[NSMutableString alloc] init];
NSMutableString *mDwdCookie = [[NSMutableString alloc] init];
for (NSHTTPCookie *cookie in cookieJar.cookies) {
//这边是做域名拦截
if ([cookie.domain containsString:@".xxxx.net"]) {
NSString *hsqCookie = [NSString stringWithFormat:@"document.cookie='%@=%@;%@=%@';", cookie.name, cookie.value, @"domain", cookie.domain];
//用来处理垮域问题
NSString *dwdCookie = [NSString stringWithFormat:@"document.cookie='%@=%@;%@=%@';", cookie.name, cookie.value, @"domain", @"yyyy.net"];
[mHsqCookie appendString:hsqCookie];
[mDwdCookie appendString:dwdCookie];
}
}
//拼接登录Cookie
if (!IsNilOrNull(loginCookie) && ![cookieValue containsString:HsqSidCookie]) {
[mHsqCookie appendString:[NSString stringWithFormat:@"document.cookie='%@domain=.xxxx.net';", loginCookie]];
[mDwdCookie appendString:[NSString stringWithFormat:@"document.cookie='%@domain=yyyy.net';", loginCookie]];
}
[cookieValue appendString:mHsqCookie];
[cookieValue appendString:mDwdCookie];
return cookieValue;
}
接口请求拿到登录Cookie保存在本地
// 保存登录cookie
- (void)saveLoginCookie:(NSURLSessionDataTask *)task
{
if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
NSDictionary *allFields = response.allHeaderFields;
NSArray<NSHTTPCookie*> *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:allFields forURL:[NSURL URLWithString:[NSString stringWithFormat:@"api地址"]]];
[cookies enumerateObjectsUsingBlock:^(NSHTTPCookie * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj.domain containsString:@".xxxx.net"] && [obj.name isEqualToString:HsqSidCookie] && ![obj.value isEqualToString:@"deleted"]) {
NSString *hsqCookie = [NSString stringWithFormat:@"%@=%@;", obj.name, obj.value];
[[NSUserDefaults standardUserDefaults] setObject:hsqCookie forKey:kDMUserLoginCookie];
[[NSUserDefaults standardUserDefaults] synchronize];
*stop = YES;
}
}];
}
}
动态同步cookie
- (WKNavigation *)reload
{
[self.configuration.userContentController removeAllUserScripts];
WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:[self updateCookies] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[self.configuration.userContentController addUserScript:cookieScript];
return [super reload];
}
网友评论