网上好多WKWebview的方法都差不多而且基本都是错的,下面是我自己整理的添加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需要先初始化一个userAgent,因为mebview获取userAgent是异步的,ios12的load时机和添加userAgent的顺序不一样,具体原因等研究下ios12代码再说...
网友评论