iOS 获取User-Agent
第一种方法
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSLog(@"-----------------%@",userAgent);
第二种方法
@interface ViewController ()<UIWebViewDelegate>
{
UIWebView *_webView;
NSString *_userAgent;
}
{
_webView = [[UIWebView alloc] init];
_webView.delegate = self;
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
NSLog(@"-----------------%@", [self userAgentString]);
}
-(NSString *)userAgentString {
while (_userAgent == nil)
{
NSLog(@"%@", @"in while");
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
return _userAgent;
}
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (webView == _webView) {
_userAgent = [request valueForHTTPHeaderField:@"User-Agent"];
// Return no, we don't care about executing an actual request.
return NO;
}
return YES;
}