iOS WKWebView添加cookie

在网络请求中,有一部分需要添加cookie,接下来就把为web添加cookie的方法小小列举一下,其实所有的要添加cookie的网络请求包括web,最终都是要在request上添加,如下:

   if (_webView == nil) {
        // 1)创建WebView
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, Kwidth, Kheight-64)];
        // 2)设置代理
        _webView.delegate = self;
        _webView.scalesPageToFit = YES;
        _webView.scrollView.bounces = NO;
    }
    // 3)设置URL地址
    NSURL *url = [NSURL URLWithString:strUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSDictionary *cookie = [AppInfo shareAppInfo].userModel.cookies;
    if (cookie != nil) {
        [request addValue:[self readCurrentCookieWith:cookie] forHTTPHeaderField:@"Cookie"];
    }else{
        [request addValue:@"" forHTTPHeaderField:@"Cookie"];
    }
    [_webView loadRequest:request];
    [self.view addSubview:_webView];

 

 

    其中获得cookie的信息我封装了一下:

#pragma mark - 拼接cookie
- (NSString*)readCurrentCookieWith:(NSDictionary*)dic{
    if (dic == nil) {
        return nil;
    }else{
        NSHTTPCookieStorage*cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        NSMutableString *cookieString = [[NSMutableString alloc] init];
        for (NSHTTPCookie*cookie in [cookieJar cookies]) {
            [cookieString appendFormat:@"%@=%@;",cookie.name,cookie.value];
        }
        //删除最后一个“;”
        [cookieString deleteCharactersInRange:NSMakeRange(cookieString.length - 1, 1)];
        return cookieString;
        
    }
} 
 [self setCookie];//设置cookie

在此之前,设置cookie。

//设置cookie 

- (void)setCookie{ 
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];  
[cookieProperties setObject:@"cookie_user" forKey:NSHTTPCookieName];  
[cookieProperties setObject:uid forKey:NSHTTPCookieValue]; [cookieProperties setObject:@"xxx.xxx.com" forKey:NSHTTPCookieDomain]; [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath]; [cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion]; [cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires]; NSHTTPCookie *cookieuser = [NSHTTPCookie cookieProperties]; [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser]; }

NSHTTPCookieStorage实现管理共享的cookie存储一个singleton对象(共享实例)。 这些cookies是所有的应用程序之间的共享和跨进程同步保存

//清除cookie 

- (void)deleteCookie{  
    NSHTTPCookie *cookie;  

    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];  

    NSArray *cookieAry = [cookieJar cookiesForURL: [NSURL URLWithString: _urlstr]]; for (cookie in cookieAry) { [cookieJar deleteCookie: cookie]; } }

转载于:https://www.cnblogs.com/lys-iOS-study/p/5856378.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值