網(wǎng)上好多WKWebview的方法都差不多而且基本都是錯(cuò)的佳鳖,下面是我自己整理的添加User-Agent的方法铜涉,兼容ios8闯团,還有最新的ios12身冬,具體代碼如下:
if (@available(iOS 12.0, *))
NSString *baseAgent = [self.myWebView valueForKey:@"applicationNameForUserAgent"];
NSString *userAgent = [NSString stringWithFormat:@"%@ YCL",baseAgent];
[self.myWebView setValue:userAgent forKey:@"applicationNameForUserAgent"];
}
JRWeakSelf(weakSelf);
[self.myWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
NSString *oldAgent = result;
if ([oldAgent rangeOfString:@"YCL"].location != NSNotFound) {
return ;
}
NSString *newAgent = [NSString stringWithFormat:@"%@ %@", oldAgent, @"YCL"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
[[NSUserDefaults standardUserDefaults] synchronize];
if (@available(iOS 9.0, *)) {
[weakSelf.myWebView setCustomUserAgent:newAgent];
} else {
[weakSelf.myWebView setValue:newAgent forKey:@"applicationNameForUserAgent"];
}
}];
代碼不用寫很多们陆,ios12需要先初始化一個(gè)userAgent,因?yàn)閙ebview獲取userAgent是異步的印叁,ios12的load時(shí)機(jī)和添加userAgent的順序不一樣蜜另,具體原因等研究下ios12代碼再說...