欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2024-02-08 12:52:28
1、相关介绍 ios在uiwebview中获取的cookie的方法:nshttpcookiestorage * ncookies = [nshttpcookiestora...

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!

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