iOS如何获取和修改UserAgent

一、如何获取UserAgent

UIWebView方式:
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
DLog(@"userAgent :%@", userAgent);
WKWebView方式:
// 注意这个方法是异步的
WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero];
[wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
   DLog(@"userAgent :%@", result);
}];
默认UserAgent输出:

Mozilla/5.0 (iPhone; CPU iPhone OS 8_4 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12H143

微信 iOS版的 :UserAgent

mozilla/5.0 (iphone; cpu iphone os 5_1_1 like mac os x) applewebkit/534.46 (khtml, like gecko) mobile/9b206 micromessenger/5.0
其中micromessenger就是自定义的

二、如何修改UserAgent

方案一,修改全局UserAgent值(这里是在原有基础上拼接自定义的字符串)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
   NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
   NSString *newUserAgent = [userAgent stringByAppendingString:@" native_iOS"];//自定义需要拼接的字符串
   NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
   [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
}
方案二,自定义UserAgent值
WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview: wkWebView];
NSString *customUserAgent = @"native_iOS";
[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":customUserAgent}];
[[NSUserDefaults standardUserDefaults] synchronize];
[self.wkWebView setCustomUserAgent:customUserAgent];
NSURL *url = [NSURL URLWithString:self.strUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url    cachePolicy:NSURLRequestUseProtocolCachePolicy                                   timeoutInterval:10.f];
[self.wkWebView loadRequest:request];
方案三
self.wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
__weak typeof(self) weakSelf = self;
[self.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
       __strong typeof(weakSelf) strongSelf = weakSelf;
       NSString *userAgent = result;
       NSString *newUserAgent = [userAgent stringByAppendingString:@" native_iOS"];
       NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
       [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
       [[NSUserDefaults standardUserDefaults] synchronize];
       [strongSelf.wkWebView setCustomUserAgent:customUserAgent];
       // needs retain because `evaluateJavaScript:` is asynchronous
       strongSelf.wkWebView = [[WKWebView alloc] initWithFrame:strongSelf.view.bounds];
 }];
 [self.wkWebView loadRequest:request];

你可能感兴趣的:(iOS开发)