iOS WKWebView 的cookie问题

作者: 张三儿 | 来源:发表于2018-07-26 14:24 被阅读7次

一个纯WkWebView的ipad app。利用cookie来控制用户长时间未操作,返回到登录页面。

iOS其实已经提供了设置cookie的方法NSHTTPCookieStorage
起初cookie是用自己定义的

[request setValue:[NSString stringWithFormat:@"%@=%@",@"FirstPagecookie", @"FirstPagecookievalue"] forHTTPHeaderField:@"Cookie"];
Snip20180726_2.png

当我们登录成功的时候下图,cookie就会自动从请求头中带入给后台,目的就是保证验证cookie。(长时间不操作cookie就会变)。


Snip20180726_3.png

#import "ViewController.h"
#import <WebKit/WebKit.h>

@interface ViewController ()<WKUIDelegate,WKNavigationDelegate>

@property (strong, nonatomic)  WKWebView *myWebView;
@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    WKUserContentController* userContentController = WKUserContentController.new;
    WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource: @"document.cookie ='TeskWKCookieKey1=TeskWKCookieValue1';document.cookie = 'TeskWKCookieKey2=TeskWKCookieValue2';"injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];

    [userContentController addUserScript:cookieScript];
    WKWebViewConfiguration* webViewConfig = WKWebViewConfiguration.new;
    webViewConfig.userContentController = userContentController;
    CGRect ViewFrame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    self.myWebView = [[WKWebView alloc] initWithFrame:ViewFrame configuration:webViewConfig];

    
    
    NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://11.0.33.212:8088/u/loginForMobile"]];
    [request setValue:[NSString stringWithFormat:@"%@=%@",@"FirstPagecookie", @"FirstPagecookievalue"] forHTTPHeaderField:@"Cookie"];

    [self.myWebView loadRequest:request];
    [self.view addSubview:self.myWebView];
    self.myWebView.navigationDelegate = self;
    self.myWebView.UIDelegate = self;

    self.myWebView.translatesAutoresizingMaskIntoConstraints = NO;


}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{

    NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;
    NSArray *cookies =[NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:response.URL];
    //读取wkwebview中的cookie 方法1
    for (NSHTTPCookie *cookie in cookies) {
                [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }

    decisionHandler(WKNavigationResponsePolicyAllow);
}

相关文章

网友评论

    本文标题:iOS WKWebView 的cookie问题

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