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;
    
}

posted on 2016-09-19 14:57  雨季的雾  阅读(1402)  评论(0编辑  收藏  举报