今天遇到了一個(gè)問題,項(xiàng)目中需要加載web界面,使用WKWebView耗內(nèi)存小、加載速度快、與JS的交互好,所以就嘗試使用WKWebView,就遇到了一個(gè)問題:request請求的url并不是原生的html,而是從服務(wù)器端獲取到的接口,只有在用戶登錄的情況下才會加載,如下圖所示:

加載不出來想要的html界面,網(wǎng)上查了好久也大概了解到時(shí)cookie的原因,需要獲取到cookie并添加到request請求中,下面是我的解決辦法:
WKWebViewConfiguration* webConfiguration = [[WKWebViewConfiguration alloc] init];
WKUserContentController* contentController = [[WKUserContentController alloc] init];
WKPreferences *preferences = [WKPreferences new];
webConfiguration.preferences = preferences;
//ESWeakSelf:這是一個(gè)宏,防止MessageHandler循環(huán)引用
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;
}
}
//下面這個(gè)取cookie的方法,每個(gè)項(xiàng)目的name值可能不一樣,要要斷點(diǎn)查看:

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));
}];
以上就是我的解決辦法,希望會對大家有些幫助,么么