这2天遇到了这个问题,这此我分享给大家。
1问题原因:WKWebView加载的网页中用到了ajax请求,但是ajax又没有带上cookie导致无法请求到数据。
解决办法如下:
navigationDelegate代理方法
- (void) webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
中添加如下代码:
pragma mark 在发送请求之前,决定是否跳转
- (void) webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
NSLog(@"decidePolicyForNavigationAction");
NSMutableString *cookie = [NSMutableString stringWithFormat:@""];
cookie=[[NSUserDefaults standardUserDefaults] objectForKey:@"cookie"];// 你所保存的cookie
// 如果请求头部不包含cookie值则需要我们去传cookie
if ([navigationAction.request allHTTPHeaderFields][@"Cookie"] && [[navigationAction.request allHTTPHeaderFields][@"Cookie"] rangeOfString:cookie].length > 0) {
decisionHandler(WKNavigationActionPolicyAllow);
} else {
NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:navigationAction.request.URL];
[request setValue:cookie forHTTPHeaderField:@"Cookie"];
//取出cookie
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//js函数
NSString *JSFuncString =
@"function setCookie(name,value,expires)\
{\
var oDate=new Date();\
oDate.setDate(oDate.getDate()+expires);\
document.cookie=name+'='+value+';expires='+oDate+';path=/'\
}";
//拼凑js字符串,按照自己的需求拼凑Cookie
NSMutableString *JSCookieString = JSFuncString.mutableCopy;
for (NSHTTPCookie *cookie in cookieStorage.cookies) {
if (![cookie.name isEqualToString:@"__cust"]) {
NSString *excuteJSString = [NSString stringWithFormat:@"setCookie('%@', '%@', 3);", cookie.name, cookie.value];
[JSCookieString appendString:excuteJSString];
NSLog(@"excuteJSString:%@",excuteJSString);
}
}
//执行js
[webView evaluateJavaScript:JSCookieString completionHandler:nil];
decisionHandler(WKNavigationActionPolicyAllow);
}
}