服务器之家

服务器之家 > 正文

iOS UIWebView 通过 cookie 完成自动登录实例

时间:2021-03-13 16:48     来源/作者:LFYPhoenix

1、相关介绍

iOSUIWebView中获取的cookie的方法:NSHTTPCookieStorage * nCookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];

再具体获取某个域的cookie:NSArray* cookiesURL = [nCookies cookiesForURL:[NSURL URLWithString:@"你的URL"]];

通过[[NSHTTPCookieStorage sharedHTTPCookieStorage]  setCookie:userCookie]方法将 cookies来保存起来,但是这样虽然可以保存cookies但是你应用退出之后还是会丢失(其实是cookies过期的问题),做好的方法是把cookies放到NSUserDefaults保存起来.

2、实现

1.在UIWebView的代理方法中实现获取cookies并将cookies放到NSUserDefaults保存起来:- (void)webViewDidFinishLoad:(UIWebView*)webView中写入

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- (void)webViewDidFinishLoad:(UIWebView*)webView{
  
  NSArray *nCookies = [[NSHTTPCookieStoragesharedHTTPCookieStorage] cookies];
  for (NSHTTPCookie *cookie in nCookies){
    if ([cookie isKindOfClass:[NSHTTPCookie class]]){
      
      if ([cookie.name isEqualToString:@"PHPSESSID"]) {
        NSNumber *sessionOnly =[NSNumber numberWithBool:cookie.sessionOnly];
        NSNumber *isSecure = [NSNumber numberWithBool:cookie.isSecure];
        NSArray *cookies = [NSArray arrayWithObjects:cookie.name, cookie.value, sessionOnly, cookie.domain, cookie.path, isSecure, nil];
        [[NSUserDefaults standardUserDefaults] setObject:cookies forKey:@"cookies"];
        break;
      }
    }
  }
}

2.获取cookies:运行之后,UIWebView加载url之前获取保存好的cookies,并设置cookies,

?
1
2
3
4
5
6
7
8
9
10
NSArray *cookies =[[NSUserDefaults standardUserDefaults] objectForKey:@"cookies"];
  if (cookies.count >0) {
    NSMutableDictionary *cookieProperties = [NSMutableDictionarydictionary];
    [cookieProperties setObject:[cookies objectAtIndex:0] forKey:NSHTTPCookieName];
    [cookieProperties setObject:[cookies objectAtIndex:1] forKey:NSHTTPCookieValue];
    [cookieProperties setObject:[cookies objectAtIndex:3] forKey:NSHTTPCookieDomain];
    [cookieProperties setObject:[cookies objectAtIndex:4] forKey:NSHTTPCookiePath];
    NSHTTPCookie *cookieuser = [NSHTTPCookiecookieWithProperties:cookieProperties];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser];
  }

注意:要在[self.webView loadRequest:req];之前设置获取cookies!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/lfyphoenix/article/details/70281683

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部