使用WKWebView
问题描述:iOS 通过WKWebView加载H5页面,H5页面中发送了post请求数据(此请求服务器会验证是否登录,判断cookie中是否存在sessionID),由于登录信息也就是sessionID没有传到H5页面(H5页面获取不到此sessionID,cookie为空),所以服务器判断该用户未登录,会重定向到登录界面,iOS会拦截该请求,所以导致请求出错。安卓这丫的没这问题。
请求302
跨目录获取不到cookie
解决方法:iOS通过注入JS代码到H5页面,把sessionID赋值到H5页面的cookie中。记得cookie要设置path路径到根目录下—document.cookie=name+'='+value+';path=/;expires='+oDate;不然其他目录下的请求访问cookie。
document.cookie=name+'='+value+';path=/;expires='+oDate;
代码可写在下面方法中:
// 导航完成时
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
或者一开始配置的时候就注册js代码
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
[config.userContentController addUserScript:[[WKUserScript alloc] initWithSource:[self setCookieToJS] injectionTime:(WKUserScriptInjectionTimeAtDocumentStart) forMainFrameOnly:YES]]
//为wkwebview 的H5代码注入js代码赋值cookie
-(NSString *)setCookieToJS{
//取出cookie
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in cookieStorage.cookies) {
NSLog(@"name = %@ value = %@",cookie.name,cookie.value);
}
//js函数
NSString *JSFuncString = @"function setCookie(name,value,expires)\
{\ var oDate=new Date();\
oDate.setDate(oDate.getDate()+expires);\
document.cookie=name+'='+value+';path=/;expires='+oDate;\
}\
function getCookie(name)\
{\
var arr = document.cookie.match(new RegExp('(^| )'+name+'=([^;]*)(;|$)'));\
if(arr != null) return unescape(arr[2]); return null;\
}\
function delCookie(name)\
{\
var exp = new Date();\
exp.setTime(exp.getTime() - 1);\
var cval=getCookie(name);\
if(cval!=null) document.cookie= name + '='+cval+';expires='+exp.toGMTString();\
}";
//拼凑js字符串
NSMutableString *JSCookieString = JSFuncString.mutableCopy;
for (NSHTTPCookie *cookie in cookieStorage.cookies) {
//判断此cookie属于当前url
if([cookie.name isEqualToString:@"JSESSIONID"] && [_urlString containsString:cookie.domain] ){
NSString *excuteJSString = [NSString stringWithFormat:@"setCookie('%@', '%@', 1);", cookie.name, cookie.value];
[JSCookieString appendString:excuteJSString];
}
}
return JSCookieString;
}
创建WKWebView的时候要配置cookie,传cookie
NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
NSMutableString *cookieValue = [NSMutableString stringWithFormat:@""];
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
// cookie重复,先放到字典进行去重,再进行拼接
for (NSString *key in cookieDic) {
NSString *appendString = [NSString stringWithFormat:@"%@=%@", key, [cookieDic valueForKey:key]]; [cookieValue appendString:appendString];
}
NSURL *url = [NSURL URLWithString:_urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:cookieValue forHTTPHeaderField:@"Cookie"];
[request addValue:@"app" forHTTPHeaderField:@"requestType"];
[self.webView loadRequest:request];
self.webView.navigationDelegate = self;
self.webView.UIDelegate = self;