关于修改UIWebView的UserAgent

最近在做项目的时候需要修改webView的UserAgent,否则webView不能请求到数据,上网查了一下,其实挺多的,最重要的就是注册默认的UserAgent, 利用registerDefaults即可,下面是源码:

 1 + (void)initialize {
 2     [super initialize];
 3     UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
 4     NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
 5     NSString *myAgent = @" xyy";
 6     if (![oldAgent hasSuffix:myAgent]) {
 7         NSString *newAgent = [oldAgent stringByAppendingString:myAgent];
 8         QLLog(@"new agent :%@", newAgent);
 9         NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
10         [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
11     }
12 }

需要移除的时候只要把最后的自己的agent去掉,然后再注册即可

 
原文地址:https://www.cnblogs.com/Shreker/p/4519755.html