欢迎来到代码驿站!

iOS代码

当前位置:首页 > 移动开发 > iOS代码

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

时间:2020-10-29 14:18:36|栏目:iOS代码|点击:

1、相关介绍

iOS在UIWebView中获取的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中写入

- (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,

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!

上一篇:iOS中时间与时间戳的相互转化实例代码

栏    目:iOS代码

下一篇:IOS实现手动截图并保存

本文标题:iOS UIWebView 通过 cookie 完成自动登录实例

本文地址:http://www.codeinn.net/misctech/17068.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有