UIWebView实现自动登陆

作者: ZhongXi | 来源:发表于2015-04-13 17:26 被阅读5016次

    IOS中UIWebView不会自动存储、读取Cookie.
    要实现UIWebView的自动登陆,需要手动存储、读取Cookie.
    1.Appelegate.m中加入以下代码

    - (void)applicationDidBecomeActive:(UIApplication *)application 
    {    
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    }
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
    {
        //存储Cookie,示例加载的URL:http://119.29.69.58:81/index
        NSURL * cookieHost = [NSURL URLWithString:@"http://119.29.69.58:81"];
        NSHTTPCookie * cookie = [NSHTTPCookie cookieWithProperties:
        [NSDictionary    dictionaryWithObjectsAndKeys:
        [cookieHost host],NSHTTPCookieDomain,
        [cookieHost path],NSHTTPCookiePath,
        @"COOKIE_NAME",NSHTTPCookieName,
        @"COOKIE_VALUE",NSHTTPCookieValue,nil]];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }
    

    2.UIWebView加载URL时设置Header

    NSURL * url = [NSURL URLWithString:@"http://119.29.69.58:81/index"];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    NSArray * cookies = [[NSHTTPCookieStorage  sharedHTTPCookieStorage] cookies];
    NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    [request setHTTPMethod:@"POST"];
    [request setHTTPShouldHandleCookies:YES];
    [request setAllHTTPHeaderFields:headers];
    [self.WebView loadRequest:request];
    

    3.退出登陆时删除Cookie

    //清空Cookie
    NSHTTPCookieStorage * myCookie = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie * cookie in [myCookie cookies])
    {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }
    
    //删除沙盒自动生成的Cookies.binarycookies文件       
    NSString * path = NSHomeDirectory();
    NSString * filePath = [path stringByAppendingPathComponent:@"/Library/Cookies/Cookies.binarycookies"];
    NSFileManager * manager = [NSFileManager defaultManager];
    [manager removeItemAtPath:filePath error:nil];
    

    相关文章

      网友评论

      • 哎中文不艾汉语:没有实现可以试试吧POST 改成GET
        f37630de6f5b:请问知道为什么post不行吗 我用post加载页面报错404
      • 2d4c16f407e8:对啊,还是没实现啊,能发个demo吗

        2d4c16f407e8:@ZPengs 不行啊,网址打不开啊
        ZPengs:@阳光明媚思密达 http://www.jianshu.com/p/7b7fb2c9c780来看这个,亲测可以。
        ZPengs:@阳光明媚思密达 估计是个标题党,我也试过了,还是没实现!
      • 2cadf0a1a3f5:webview内嵌网页,做离线缓存,怎么同步用户信息?登录之后,个人中心还是登录界面,求解
      • CoderChou:@iGeekXi 求个demo
      • CoderChou:有实现的没
      • 水亮:我也是没能实现,求 demo :smile:
        liyaoyao:@水亮 请问你的现在实现了没有?
      • 8e15487cae51:有没有demo,按照你写的方法还是不能实现。
      • 清眸如画:请问 “UIWebView实现自动登陆” 是怎样一种情形

      本文标题:UIWebView实现自动登陆

      本文链接:https://www.haomeiwen.com/subject/lgvkfttx.html