原文地址:https://blog.csdn.net/sinco25/article/details/128486770
需求
有一个完全是web的app项目,用WKWebView包装。在第一次登录以后,保持session有效,下次开app自动进入已登录的首页。
实现:
主要是按host分别记录和使用cookie,比如:www.foo.com和www.baidu.com的cookie不能混着
- (void)viewDidLoad {
self.toUrl = [NSURL URLWithString:@"http://foo.com:8090/xxx.html"];
self.urlHost = self.toUrl.host;
}
登录后把cookie存在本地
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
//本地存储
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *cookieDic = [[NSMutableDictionary alloc] initWithDictionary:[userDefault objectForKey:self.urlHost]];
//取出cookie,写进本地存储
WKHTTPCookieStore * wkcookieStore = [WKWebsiteDataStore defaultDataStore].httpCookieStore;
[wkcookieStore getAllCookies:^(NSArray<NSHTTPCookie *> * _Nonnull cookies) {
NSArray* allCookis=cookies;
for (NSHTTPCookie *cookie in allCookis) {
NSLog(@"cookie: %@",cookie);
[cookieDic setObject:[cookie properties] forKey:cookie.name];
}
[userDefault setObject:cookieDic forKey:self.urlHost];
}];
decisionHandler(WKNavigationResponsePolicyAllow);
}
把cookie注入到WKWebsiteDataStore
一定要在WKWebView实例化之前做注入
//注入cookie
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
NSDictionary* cookieDic = [userDefault objectForKey:self.urlHost];
for (NSString *key in cookieDic) {
NSDictionary* obj =[cookieDic objectForKey:key];
NSHTTPCookie *cookie = [[NSHTTPCookie alloc] initWithProperties:obj];
[[WKWebsiteDataStore defaultDataStore].httpCookieStore setCookie:cookie completionHandler:nil];
}
//注入后再实例化
self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:webConfig];
[self.webView loadRequest:[NSURLRequest requestWithURL:self.toUrl]];