iOSUIWebView如何通过cookie完成自动登录
这篇文章主要为大家展示了“iOS UIWebView如何通过cookie完成自动登录”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“iOS UIWebView如何通过cookie完成自动登录”这篇文章吧。
创新互联公司主要从事成都网站设计、成都网站制作、外贸网站建设、网页设计、企业做网站、公司建网站等业务。立足成都服务新会,10年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18980820575
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 UIWebView如何通过cookie完成自动登录”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!
分享名称:iOSUIWebView如何通过cookie完成自动登录
浏览路径:http://cdiso.cn/article/gcjhhg.html