iOS 9.0 開始为流,有如下API,可以自定義user agent
@property (nullable, nonatomic, copy) NSString *customUserAgent API_AVAILABLE(macosx(10.11), ios(9.0));
但是有些第三方網(wǎng)頁是通過系統(tǒng)默認(rèn)的user agent來進行頁面適配磺陡,那么也需要默認(rèn)的那部分user agent趴梢,根據(jù)iOS系統(tǒng)不同,user agent也不一樣币他;
如12.3.1系統(tǒng)對應(yīng)的user agent為:Mozilla/5.0 (iPhone; CPU iPhone OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;
可以通過js獲取原有agent,然后進行賦值操作坞靶;如:
__weak typeof(self) weakSelf = self;
[self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable agent, NSError * _Nullable error) {
NSString *oldAgent = agent;
// 給User-Agent添加額外的信息
NSString *newAgent = [NSString stringWithFormat:@"%@;%@", oldAgent, @"custom-app"];
weakSelf.webView.customUserAgent = newAgent;
}];
如果要進行適配iOS8系統(tǒng),則需要使用官方提供的另外一種方法蝴悉,全局修改user agent
[self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable agent, NSError * _Nullable error) {
NSString *oldAgent = agent;
// 給User-Agent添加額外的信息
NSString *newAgent = [NSString stringWithFormat:@"%@;%@", oldAgent, @"custom-app"];
// 設(shè)置global User-Agent
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
}];
如果在WKWebView所在的ViewController,會出現(xiàn)第二次打開webView的時候彰阴,才會起效等問題;這里更傾向于在App delegate中拍冠,直接全局修改尿这;申明一個變量webview進行user agent的賦值操作;要注意庆杜,單獨聲明的WKWebView的作用域的問題射众,此方法是異步方法;