今天遇到了一個問題雏胃,項目中需要加載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循環(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;
}
}
//下面這個取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));
}];
以上就是我的解決辦法衷畦,希望會對大家有些幫助栗涂,么么