iOS UIWebView 通过 cookie 完成自动登录实例
1、相关介绍
iOS在UIWebView中获取的cookie的方法:NSHTTPCookieStorage*nCookies=[NSHTTPCookieStoragesharedHTTPCookieStorage];
再具体获取某个域的cookie:NSArray*cookiesURL=[nCookiescookiesForURL:[NSURLURLWithString:@"你的URL"]];
通过[[NSHTTPCookieStoragesharedHTTPCookieStorage] 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*cookieinnCookies){ if([cookieisKindOfClass:[NSHTTPCookieclass]]){ if([cookie.nameisEqualToString:@"PHPSESSID"]){ NSNumber*sessionOnly=[NSNumbernumberWithBool:cookie.sessionOnly]; NSNumber*isSecure=[NSNumbernumberWithBool:cookie.isSecure]; NSArray*cookies=[NSArrayarrayWithObjects:cookie.name,cookie.value,sessionOnly,cookie.domain,cookie.path,isSecure,nil]; [[NSUserDefaultsstandardUserDefaults]setObject:cookiesforKey:@"cookies"]; break; } } } }
2.获取cookies:运行之后,UIWebView加载url之前获取保存好的cookies,并设置cookies,
NSArray*cookies=[[NSUserDefaultsstandardUserDefaults]objectForKey:@"cookies"]; if(cookies.count>0){ NSMutableDictionary*cookieProperties=[NSMutableDictionarydictionary]; [cookiePropertiessetObject:[cookiesobjectAtIndex:0]forKey:NSHTTPCookieName]; [cookiePropertiessetObject:[cookiesobjectAtIndex:1]forKey:NSHTTPCookieValue]; [cookiePropertiessetObject:[cookiesobjectAtIndex:3]forKey:NSHTTPCookieDomain]; [cookiePropertiessetObject:[cookiesobjectAtIndex:4]forKey:NSHTTPCookiePath]; NSHTTPCookie*cookieuser=[NSHTTPCookiecookieWithProperties:cookieProperties]; [[NSHTTPCookieStoragesharedHTTPCookieStorage]setCookie:cookieuser]; }
注意:要在[self.webViewloadRequest:req];之前设置获取cookies!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。