在webView中,有时候我们不可避免的需要重新设置webView的UA信息或者 是添加部分的自定义字段上传,以下是我们项目的一个案例:
// 如果这个方法的返回值是YES的话就继续加载这个请求,如果是NO的话就不加载了
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
//拦截URL,判断http或https请求头部信息
if ([parseRet[@"protocol"] isEqualToString:@"http"] || [parseRet[@"protocol"] isEqualToString:@"https"]) {
NSMutableURLRequest *mutableRequest = [navigationAction.request mutableCopy];
NSDictionary *headFields = mutableRequest.allHTTPHeaderFields;
NSString * uuid = headFields[@"MDEVICEID"];//登录的token
//判断请求头是否存在uuid字段,如果否,则表示该请求尚未设置请求头
if ([uuid length] == 0) {
//IDFA
//此处需要传的是客户端的uuid
NSString* uuid = [MTDGlobalObject shareGlobalObject].uuid;
if (uuid && ![uuid isEqualToString:@""]) {
[mutableRequest addValue:uuid forHTTPHeaderField:@"MDEVICEID"];
} else {
[mutableRequest addValue:@"" forHTTPHeaderField:@"MDEVICEID"];
}
//登录头部信息,自定义的登录字段等
MTDUserModel *user = [MTDGlobalObject shareGlobalObject].currentUser;
[mutableRequest setValue:user.userAuthToken ? user.userAuthToken :@"" forHTTPHeaderField:@"MAUTH"];
[mutableRequest setValue:user.userAuthCode?user.userAuthCode : @"" forHTTPHeaderField:@"MAUTHCODE"];
//重新加载设置后的请求
[webView loadRequest:mutableRequest];
}
}
decisionHandler(WKNavigationActionPolicyAllow);//允许跳转
}
设置webView的全局UA
//该设置针对的是全局webView的UA变更
- (void)setWebViewUA
{
//修改webView UA
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero];
_wkwebView = webView;
//获取自定义的UA重置字符串
NSString *UA = [[MTDGlobalObject shareGlobalObject] getUAStr:MTDUATypeWebView];
//替换本地中的UA内容
[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":UA}];
[[NSUserDefaults standardUserDefaults] synchronize];
//设置webView的UA
[_wkwebView setCustomUserAgent:UA];
}
网友评论