在和前端交互過程中育勺,為了區(qū)分是我們APP內(nèi)加載網(wǎng)頁還是其他應(yīng)用或瀏覽器加載的網(wǎng)頁姐呐,我們需要使用在UserAgent后追加字符串來區(qū)分聚至。下面介紹全局和局部修改UserAgent化戳。
設(shè)置全局UserAgent
下面兩種方法都可以修改全局UserAgent宜雀,因為修改的是系統(tǒng)配置切平,等于全局公用屬性,所以不論使用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初始化要放在設(shè)置UserAgent后才會生效。
- 需要注意的是在當(dāng)前頁面銷毀后夸研,設(shè)置的UserAgen就會失效邦蜜,如果push或者present后面的頁面,UserAgen依然有效亥至。
- AppDelegate不會銷毀以一直有效
設(shè)置局部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);
}];
總結(jié):
- WKWebView需要等待回調(diào)才能設(shè)置UserAgent贱迟;
- UIWebView可以直接返回UserAgent效率更高;