iOS WKWebView 添加 cookie

今天遇到了一个问题,项目中需要加载web界面,使用WKWebView耗内存小、加载速度快、与JS的交互好,所以就尝试使用WKWebView,就遇到了一个问题:request请求的url并不是原生的html,而是从服务器端获取到的接口,只有在用户登录的情况下才会加载,如下图所示:

加载不出来想要的html界面,网上查了好久也大概了解到时cookie的原因,需要获取到cookie并添加到request请求中,下面是我的解决办法:

WKWebViewConfiguration* webConfiguration = [[WKWebViewConfiguration alloc] init];

WKUserContentController* contentController = [[WKUserContentController alloc] init];

WKPreferences *preferences = [WKPreferences new];

webConfiguration.preferences = preferences;

//ESWeakSelf:这是一个宏,防止MessageHandler循环引用

ESWeakSelf

[contentController addScriptMessageHandler:__weakSelf name:@"rule"];

[contentController addScriptMessageHandler:__weakSelf name:@"minimalInvasiveActivityProtocolClick"];

self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight-64) configuration:webConfiguration];

self.webView.navigationDelegate = self;

self.webView.UIDelegate = self;

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.urlString]];

/******************************获取cookies***********************************/

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

NSHTTPCookie* realCookie = nil;

for (NSHTTPCookie* cookie in cookies) {

//[NSObject baseURLStr] :接口地址的请求头

NSRange range = [[NSObject baseURLStr] rangeOfString:cookie.domain];

//如过找到了

if (range.location != NSNotFound) {

realCookie = cookie;

break;

}

}

//下面这个取cookie的方法,每个项目的name值可能不一样,要要断点查看:

NSString* cookieValue = [NSString stringWithFormat:@"app=%@;",realCookie.value];

[request setValue:cookieValue forHTTPHeaderField:@"Cookie"];

/******************************获取cookies***********************************/

if (self.urlString) {

[self.webView loadRequest:request];

}

else if (self.htmlString)

{

[self.webView loadHTMLString:self.htmlString baseURL:nil];

}

[self.view addSubview:self.webView];

[self.webView mas_makeConstraints:^(MASConstraintMaker *make) {

make.edges.mas_offset(UIEdgeInsetsMake(0, 0, 0, 0));

}];

以上就是我的解决办法,希望会对大家有些帮助,么么

推荐阅读更多精彩内容