美文网首页杂乱
iOS 关于UIWebView设置cookie

iOS 关于UIWebView设置cookie

作者: Refusing | 来源:发表于2018-06-26 16:53 被阅读17次

    最近在做一个项目,里面用到webview进行处理一些界面, 但是前提是需要在登录状态下.所以就处理一下方法

    1. 在请求的时候进行cookie注入

    // 在请求网站之前先把所有的cookie删除,然后注入需要的cookie

    [self deleteCookie], [self setCookie]; 

    [self.webView loadRequest:request];

    2.在开始加载的时候进行cookie注入

    //webView代理   开始加载

    - (void)webViewDidStartLoad:(UIWebView*)webView{

    NSLog(@"已经开始加载");

    [self deleteCookie], [self setCookie];

    }

    设置cookie方法

    //设置cookie

    - (void)setCookie {

    NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];

    [cookieProperties setObject:@"PHPSESSID" forKey:NSHTTPCookieName];

    [cookieProperties setObject:@"sessionID" forKey:NSHTTPCookieValue];

    [cookieProperties setObject:@"www.baidu.com" forKey:NSHTTPCookieDomain];

    [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];

    [cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];

    [cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:30*24*60*60] forKey:NSHTTPCookieExpires];

    NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];

    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

    }

    清除cookie方法

    //清除cookie

    - (void)deleteCookie{

    NSHTTPCookie *cookie;

    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

    // 获取到www.baidu.com下的cookies   

    NSArray *cookieAry = [cookieJar cookiesForURL: [NSURL URLWithString:@"www.baidu.com"]];

    for (cookie in cookieAry) {

    [cookieJar deleteCookie: cookie];

    }

    // 获取到所有的cookies

    NSArray *cookieAry2 = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];

    for (cookie in cookieAry2) {

    [cookieJar deleteCookie: cookie];

    }

    }

    相关文章

      网友评论

        本文标题:iOS 关于UIWebView设置cookie

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