最近做了一個項目,加載網(wǎng)頁使用的是WKWebView艳丛,網(wǎng)頁需要同步客戶端登錄后的cookie匣掸。
UIWebView加載cookie簡述
在之前使用UIWebView時,因為UIWebView共用NSHTTPCookieStorage的cookie氮双,h5頁面同步cookie不需要做特別的處理碰酝。一般的流程是:登錄請求成功后Cookie會自動保存在NSHTTPCookieStorage,然后將NSHTTPCookieStorage的cookie取出保存到NSUserDefaults戴差,下次打開應(yīng)用就將NSUserDefaults中保存的cookie設(shè)置到NSHTTPCookieStorage中送爸,然后整個項目中發(fā)送的網(wǎng)絡(luò)請求就都會帶有設(shè)置的cookie。
當(dāng)然UIWebView也可以設(shè)置request [request addValue:cookieValue forHTTPHeaderField:@"Cookie"]; 來添加cookie暖释。
WKWebView添加cookie
到WKWebView后袭厂,它不會去獲取NSHTTPCookieStorage中的cookie,就需要我們自己設(shè)置了球匕。
首先在loadRequest的時候給request設(shè)置cookie
NSMutableString *cookieValue = [[NSMutableString alloc] initWithString:@"document.cookie = 'from=ios';"];
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [cookieJar cookies]) {
NSString *appendString = [NSString stringWithFormat:@"%@=%@;", cookie.name, cookie.value];
[cookieValue appendString:appendString];
}
[request addValue:cookieValue forHTTPHeaderField:@"Cookie"];
這樣做了之后纹磺,在打開頁面時是帶有cookie的,也就是已登錄的狀態(tài)亮曹,但是當(dāng)你點(diǎn)頁面的鏈接跳轉(zhuǎn)橄杨,新的頁面卻沒有帶上cookie秘症。我們就要在初始化WKWebView時,在configuration中設(shè)置帶有cookie的userContent式矫。代碼:
//各個WKWebview使用同一個WKProcesspool
config = [[WKWebViewConfiguration alloc] init];
config.preferences = [[WKPreferences alloc] init];
config.preferences.minimumFontSize = 10.0;
config.preferences.javaScriptEnabled = YES;
config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
config.processPool = [[WKProcessPool alloc] init];
//添加Cookie
NSMutableString *cookieValue = [[NSMutableString alloc] initWithString:@"document.cookie = 'from=ios';"];
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [cookieJar cookies]) {
NSString *appendString = [NSString stringWithFormat:@"%@=%@;", cookie.name, cookie.value];
[cookieValue appendFormat:@"document.cookie='%@';", appendString];
}
WKUserContentController* userContentController = WKUserContentController.new;
WKUserScript * cookieScript = [[WKUserScript alloc]
initWithSource: cookieValue
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];
config.userContentController = userContentController;