iOS - User Agent 的应用和设置

 

UA在项目中的应用

  给项目的webview或项目中的接口请求加一个区分,用来区别是iOS端访问、android访问还是在浏览器访问的,这时需要添加User Agent (http请求 header中的一个参数)

  1)什么是User Agent? 1. 用户代理 User Agent,是指浏览器,它的信息包括硬件平台、 系统软件、应用软件和用户个人偏好。 2. 早的时候有一个浏览器叫NCSA Mosaic,把自己标称为 NCSA_Mosaic/2.0 (Windows 3.1),它支持文字显示的同时还支持图片,于是Web开始好玩起来。 3. 通过浏览器navigator.userAgent,可以获得用户的UserAgent。 4. UserAgent简称UA,可以用作一个用户的真实访问,一般的Web统计流量也会针对UA信息去统计浏览器占比,移动占比等等。


  2)webview全局的设置两种方法:

      //1.直接在app delegate 里面设置(这种方法比较简单,其中具体的参数自己选择性的设置)

        - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

        //修改app默认UA

        UIWebView* tempWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
        NSString* userAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
        //        NSLog(@"------%@",userAgent);
        NSString *executableFile = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleExecutableKey];
        NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];
        NSString *ua = [NSString stringWithFormat:@"%@ %@/%@", userAgent, executableFile,version];
        //        NSLog(@"------%@",ua);
        [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent" : ua, @"User-Agent" : ua}];
    
        return YES; }    
         
  

       //  2.第二种方法
                                                                                      
      //在webView:shouldStartLoadWithRequest:navigationType:方法中同步加载到request的data,然后使用UIWebView的-loadData:MIMEType:textEncodingName:baseURL:方法加载data

    - (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
      {
      if (...) {
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSHTTPURLResponse *response = nil;
        NSError *error = nil;
        NSData *data = [NSURLConnection sendSynchronousRequest:request
                                             returningResponse:&response
                                                         error:&error];
        if (error) {
            // ...
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.webView loadData:data
                          MIMEType:response.MIMEType
                  textEncodingName:response.textEncodingName
                           baseURL:request.URL];
        });
    });
    return NO;
}
return YES;
}

 

        3) 一般的网络请求在request 

      

// AFN中 在 AFHTTPRequestSerializer 类中
//调用- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(NSString*)field; 给请求头设置参数 @"User-Agent" 的值

 

 

 

 

          

    

posted @ 2018-05-09 18:38  俊华的博客  阅读(5502)  评论(0编辑  收藏  举报