一. UIWebView
在使用 UIWebView 的時候,我們是通過 NSHTTPCookieStorage 來管理 cookie 的,我們給 momo.domain.com 域名添加一個名字為 user 的 cookie,代碼類似下面。
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"user" forKey:NSHTTPCookieName];
[cookieProperties setObject:@"xxxxxx" forKey:NSHTTPCookieValue];
[cookieProperties setObject:@"momo.domain.com" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
這樣就完成了給UIWebView設置 cookie 的工作。
在 WKWebView 中通過 NSHTTPCookieStorage 來設置 cookie 是行不通的,要通過 URLRequest 來添加 cookie 才能起效果 。代碼類似下面。
二. WKWebView
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://momo.domain.com"]];
NSDictionary *headFields = request.allHTTPHeaderFields;
NSString *cookie = headFields[@"user"];
if (cookie == nil) {
[request addValue:[NSString stringWithFormat:@"user=%@", @"userValue"] forHTTPHeaderField:@"Cookie"];
}
[self.webView loadRequest:request];
你以為 WKWebView 添加 cookie 就這樣結束了 ? 其實遠遠沒有。上面通過 URLRequest 來添加 cookie 的方式只能對 WKWebView loadRequest 的那個 request 起作用,如果你的 WKWebView 加載的 Web 頁面包含了 ajax 請求的話,那 cookie 又要重新處理了,這個處理需要在 WKWebView 的 WKWebViewConfiguration 中進行配置。代碼類似下面。
//應用于 ajax 請求的 cookie 設置
WKUserContentController *userContentController = WKUserContentController.new;
NSString *cookieSource = [NSString stringWithFormat:@"document.cookie = 'user=%@';", @"userValue"];
WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:cookieSource injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.userContentController = userContentController;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://momo.domain.com"]];
// 應用于 request 的 cookie 設置
NSDictionary *headFields = request.allHTTPHeaderFields;
NSString *cookie = headFields[@"user"];
if (cookie == nil) {
[request addValue:[NSString stringWithFormat:@"user=%@", @"userValue"] forHTTPHeaderField:@"Cookie"];
}
self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:config];
[self.webView loadRequest:request];
三 使用Safari調試 cookie
1.首先先用真機或者模擬器打開一個網頁
2.打開Safari,然后選擇開發(fā)選項

image.png
3.選擇 存儲空間 -> cookie 管理,即可看到相關 cookie 了

image.png
本文參考 WKWebView 設置 Cookie
同類文章參考
1.《 WKWebView 那些坑》
2.獻上蘋果工程師在官方論壇的一個關于 WKWebView Cookie 問題的答復