ios-webview登录

ios webview登录最重要的就是将登陆之后的cookie存起来
在ios12之前我们登录都能正常从- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler方法中取到response之后,直接处理成cookie存起来
但是ios12开始 此方法登录就取不到response里最重要的set-cookie的值 我们就只能在h5那边登录之后的页面取到cookie经过字符串处理 将他们存起来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
-(void)loginSuccess:(NSHTTPURLResponse*)response orWithCookie:(NSString*)cookie{
//清除之前的coockie
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *_tmpArray = [NSArray arrayWithArray:[cookieJar cookies]];
for (id obj in _tmpArray) {
[cookieJar deleteCookie:obj];
}
// 删除NSUserDefault里面的值
NSUserDefaults *defatluts = [NSUserDefaults standardUserDefaults];
NSDictionary *dictionary = [defatluts dictionaryRepresentation];
for(NSString *key in [dictionary allKeys]){
if([key isEqualToString:@"cookie"]){
[defatluts removeObjectForKey:key];
}
[defatluts synchronize];
}
//读取wkwebview中的cookie 方法
NSArray *cookies =[NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL: response.URL];
if (cookies.count <= 0){
NSString *b =[[self achieveStringWithRootString:cookie key:@"_ResumeHack_session"] stringByAppendingString:@" path=/; HttpOnly, "];
NSMutableArray* mcookies = [cookies mutableCopy];
[mcookies addObject:[b cookie]];
cookies = [NSArray arrayWithArray:mcookies];
}

for (NSHTTPCookie *cookie in cookies) {
//将 cookie 存进NSHTTPCookieStorage
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
//把cookie存到NUserDefault里面
NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: cookiesData forKey: @"cookie"];
[defaults synchronize];
NSLog(@"userdefault中的cookie%@",[defaults objectForKey:@"cookie"]);

//看看存入到了NSHTTPCookieStorage了没有
NSHTTPCookieStorage *cookieJar2 = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in cookieJar2.cookies) {
NSLog(@"NSHTTPCookieStorage中的cookie%@", cookie);
}

[self dismissViewControllerAnimated:YES completion:^{
_loginComplete();
}];
[Loading hide];
}

字符串处理cookie

1
2
3
4
5
6
7
8
- (NSString *)achieveStringWithRootString:(NSString *)rootString key:(NSString *)key{
NSRange aRange = [rootString rangeOfString:[NSString stringWithFormat:@"%@=",key]];
NSString *c = [rootString substringFromIndex:aRange.location];
NSLog(@"c===============%@", c);
NSRange bRange = [c rangeOfString:@";"];//匹配得到的下标
NSString *d = [c substringToIndex:bRange.location + bRange.length];
return d;
}

ps:在登录、登出中清除cookie跟userdefault中的值的时候要避免清除其他有用的值 否则会导致userdefault值的丢失 造成很奇怪的bug