在和前端交互过程中,为了区分是我们APP内加载网页还是其他应用或浏览器加载的网页,我们需要使用在UserAgent后追加字符串来区分。下面介绍全局和局部修改UserAgent。
设置全局UserAgent
下面两种方法都可以修改全局UserAgent,因为修改的是系统配置,等于全局公用属性,所以不论使用UIWebView还是WKWebview,修改都是同一个属性。
方法一:WKWebView配置UserAgent
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.webView = [[WKWebView alloc] init];
[self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
NSString *userAgent = result;
NSString *newUserAgent = [userAgent stringByAppendingString:@" Appended Custom User Agent"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
}];
return YES;
}
注意:WKWebView不能使用局部声明,需要放在类扩展中,否则无效
方法二:UIWebView配置UserAgent
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIWebView *webView = [[UIWebView alloc] init];
NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString *newUserAgent = [userAgent stringByAppendingString:@" Appended Custom User Agent"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
return YES;
}
- 方法二放在其他ViewController也是可以使用,webView初始化要放在设置UserAgent后才会生效。
- 需要注意的是在当前页面销毁后,设置的UserAgen就会失效,如果push或者present后面的页面,UserAgen依然有效。
- AppDelegate不会销毁以一直有效
设置局部UserAgent
UIWebView *tempWebView = [[UIWebView alloc] init];
NSString *userAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString *newUserAgent = [userAgent stringByAppendingString:@" Appended Custom User Agent"];
self.webView.customUserAgent = newUserAgent;
// 下面这句了打印userAgent,可以不要
[self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
NSLog(@"%@", result);
}];
总结:
- WKWebView需要等待回调才能设置UserAgent;
- UIWebView可以直接返回UserAgent效率更高;
网友评论