iOS:WKWebView之cookie请求

说明
首次发表 2017年11月14
最近更新 2019年03月18日

先贴出清除cookie的代码:

#pragma mark - *************** 清除cookies
- (void)clearAllCookies {
    
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [storage cookies]) {
        [storage deleteCookie:cookie];
    }
}

cookie代码如下:

iOS:WKWebView之cookie请求_第1张图片
图片.png

贴上代码:

#import "MJWebVC.h"

//Libs
#import 

@interface MJWebVC ()

@property(nonatomic, strong) WKWebView *webView;
@property(nonatomic, strong) UIProgressView *progress;

@end

@implementation MJWebVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *url = [NSString stringWithFormat:@"%@?accessToken=%@", self.urlStr, kRT];
    [self loadRequestWithUrlString:url];
    
    //TODO:kvo监听,获得页面title和加载进度值
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progress];
}

- (void)loadRequestWithUrlString:(NSString *)urlString {
    
    // 在此处获取返回的cookie
    NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
    
    NSMutableString *cookieValue = [NSMutableString stringWithFormat:@""];
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        [cookieDic setObject:cookie.value forKey:cookie.name];
    }
    
    // cookie重复,先放到字典进行去重,再进行拼接
    for (NSString *key in cookieDic) {
        NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
        [cookieValue appendString:appendString];
    }
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [request addValue:cookieValue forHTTPHeaderField:@"Cookie"];
    
    [self.webView loadRequest:request];
}


#pragma mark - *************** 监听

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    //加载进度值
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        if (object == self.webView) {
            [self.progress setAlpha:1.0f];
            [self.progress setProgress:self.webView.estimatedProgress animated:YES];
            if(self.webView.estimatedProgress >= 1.0f) {
                [UIView animateWithDuration:0.5f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                    [self.progress setAlpha:0.0f];
                } completion:^(BOOL finished) {
                    [self.progress setProgress:0.0f animated:NO];
                }];
            }
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    } else if ([keyPath isEqualToString:@"title"]) {//网页title
        if (object == self.webView) {
            self.navigationItem.title = self.webView.title;
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


#pragma mark - *************** 销毁的时候,一定要移除监听

- (void)dealloc {
    
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
    
}


#pragma mark - *************** WKNavigationDelegate代理

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
    
    
}

// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
    
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    
    
}


#pragma mark - *************** lazy load

- (WKWebView *)webView {
    if (!_webView) {
        _webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
    }
    return _webView;
}

- (UIProgressView *)progress {
    if (!_progress) {
        _progress = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 64, MJScreenWidth, 2)];
        _progress.tintColor = [UIColor blueColor];
        _progress.backgroundColor = [UIColor lightGrayColor];
    }
    return _progress;
}

@end

另外附上其他需要cookie请求的代码:

AFNetworking:

// 获取AFHTTPRequestOperationManager
    AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];

    // 创建可变字典用于存放Cookie
    NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];

    // 存放新添加的cookie
    #warning 单个的Cookie还好,但是楼主在工厂类方法中拼接了一个包含6个设备信息的value值,最后忘记加分号了,测试也没测出来
    #warning 因为不影响功能,但是后面的cookie就自动拼接上了,H5那边也识别不到,险造成重大事故(涉及金融。。),望后来者看到,提前做好准备(就凭这个坑,你得给我个赞)
    NSMutableString *cookieValue = [NSMutableString stringWithFormat:@"fromapp=ios;"];

    // 获取
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        [cookieDic setObject:cookie.value forKey:cookie.name];
    }

    // cookie重复,先放到字典去重,再进行拼接
    for (NSString *key in cookieDic) {
        NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
        [cookieValue appendString:appendString];
    }

    // 将cookie存到请求头中
    [operationManager.requestSerializer setValue:cookieValue forHTTPHeaderField:@"Cookie"];

    //  拼接url地址
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", kHostIP, kPath];

    // 设置参数字典
    NSDictionary *paraDict = @{
                                  @"key" : value
                                  };
    // 发送请求,处理结果
    [operationManager POST:urlStr parameters:paraDict success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {

         NSLog(@"responseObject-->%@", responseObject);

    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {

         NSLog(@"error-->%@", error);
    }];

WKWebView:

如果WKWebView在加载url的时候需要添加cookie,需要先手动获取当前NSHTTPCookieStorage中的所有cookie,然后将cookie放到NSMutableURLRequest请求头中

- (void)loadRequestWithUrlString:(NSString *)urlString {

    // 在此处获取返回的cookie
    NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];

    NSMutableString *cookieValue = [NSMutableString stringWithFormat:@""];
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        [cookieDic setObject:cookie.value forKey:cookie.name];
    }

    // cookie重复,先放到字典进行去重,再进行拼接
    for (NSString *key in cookieDic) {
        NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
        [cookieValue appendString:appendString];
    }

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [request addValue:cookieValue forHTTPHeaderField:@"Cookie"];

    [self loadRequest:request];
}

UIWebView:

// 工厂类中存储cookie的方法
+ (void)saveCookies {
    // 创建一个可变字典存放cookie
    NSMutableDictionary *fromappDict = [NSMutableDictionary dictionary];
    [fromappDict setObject:@"fromapp" forKey:NSHTTPCookieName];
    [fromappDict setObject:@"ios" forKey:NSHTTPCookieValue];
    // kDomain是公司app网址
    [fromappDict setObject:kDomain forKey:NSHTTPCookieDomain];
    [fromappDict setObject:kDomain forKey:NSHTTPCookieOriginURL];
    [fromappDict setObject:@"/" forKey:NSHTTPCookiePath];
    [fromappDict setObject:@"0" forKey:NSHTTPCookieVersion];

    // 将可变字典转化为cookie
    NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:fromappDict];

    // 获取cookieStorage
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]

    // 存储cookie
    [cookieStorage setCookie:cookie];
}
注意:
  • UIWebView使用时间较长,只要在cookieStorage中设置了相应的cookie,每次就会自动带上;
  • 但是这样的弊端是随着与H5的交互增加,Cookie占用的空间越来越大,每次交互都夹带大量的cookie,不仅增加服务器端压力,也浪费用户的流量。比如每次交互都夹带5kb的cookie内容,但是真正用到的只有两三百字节。

后记:吃水不忘挖井人,感谢si1ence提供的帮助!

你可能感兴趣的:(iOS:WKWebView之cookie请求)