分享

iPhone获得User-Agent(UA)信息的方法

 ccccshq 2014-07-15

User-Agent(简称UA)是HTTP请求头部用来标识客户端信息的字符串, 包括操作系统, 浏览器等信息. 为了建立手机客户端的信息数据库, 需要从手机的http请求中取到这一字符串.

AD:WOT2014:用户标签系统与用户数据化运营培训专场

如果你需要获取Android手机的UA信息,请移步这里Android获得UA信息的方法

iPhone中取到UA信息的方法如下:

1.利用浏览器控件UIWebView建立一个http请求

2.在请求建立的期间, 建立一个新的事件循环用来判断UA信息是否已经建立

3.在发送http请求之前截获UA信息, 并且取消这一http请求 ;)

获取iPhone UA的代码如下:

  1. UIWebView *_webView; 
  2. NSString *userAgent; 
  3.  
  4. - (void)createHttpRequest { 
  5.     _webView = [[UIWebView alloc] init]; 
  6.     _webView.delegate = self; 
  7.     [_webView loadRequest:[NSURLRequest requestWithURL: 
  8.     [NSURL URLWithString:@"http://www."]]]; 
  9.     NSLog(@"%@", [self userAgentString]); 
  10.     [_webView release]; 
  11.  
  12. -(NSString *)userAgentString 
  13.     while (self.userAgent == nil)  
  14.     { 
  15.         NSLog(@"%@", @"in while"); 
  16.         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; 
  17.         } 
  18.     return self.userAgent; 
  19.  
  20. -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 
  21.     if (webView == _webView) { 
  22.     self.userAgent = [request valueForHTTPHeaderField:@"User-Agent"]; 
  23.     // Return no, we don't care about executing an actual request. 
  24.     return NO; 
  25.     return YES; 
  26.  
  27. - (void)dealloc { 
  28. [userAgent release]; 
  29.     [super dealloc]; 
  30.   

程序在iPhone4.1模拟器中运行结果如下:

2010-12-21 12:52:38.302 UATest[6722:207] in while

2010-12-21 12:52:38.305 UATest[6722:207] in while

2010-12-21 12:52:38.307 UATest[6722:207] in while

2010-12-21 12:52:38.307 UATest[6722:207] in while

2010-12-21 12:52:38.308 UATest[6722:207] in while

2010-12-21 12:52:38.309 UATest[6722:207] in while

2010-12-21 12:52:38.312 UATest[6722:207] Mozilla/5.0 (iPhone Simulator; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/8B117

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多