zoukankan      html  css  js  c++  java
  • 设置User Agent

      公司的前端要给项目的webview加一个区分,用来区别是iOS端访问、android访问还是在浏览器访问的,说是要加一个User Agent ,前端根据不同信息做适配,和我说来一头雾水,后来经过开发同事的指导和在网上查阅资料,才有了点头绪,在这里和大家分享一下。

    一、获取UserAgent

    UIWebView方式:
    UIWebView* tempWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString* userAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSLog(@"UIWebView默认的userAgent = %@", userAgent);
    默认UserAgent输出:
    UIWebView默认的userAgent = Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E304
     二、修改UserAgent
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
       UIWebView* tempWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
       NSString* userAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
       NSLog(@"UIWebView默认的userAgent = %@", userAgent);
       NSString *versionsss = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];;
       NSString *ua = [NSString stringWithFormat:@"%@/XYWY_YIMAI/iOS/%@", userAgent, versionsss];//自定义需要拼接的字符串
       [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent" : ua, @"User-Agent" : ua}];
    }
    获取UserAgent输出:
    NSMutableURLRequest *request = .....
    
    /** 获取系统的UA */
    NSString *sysUA = request.allHTTPHeaderFields[@"User-Agent"];

    最终得到修改后的:

    Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E304/XYWY_YIMAI/iOS/5.5
  • 相关阅读:
    仓鼠找sugar(LCA)
    bzoj4481非诚勿扰(期望dp)
    NOIP2011Mayan游戏(模拟)
    [国家集训队]旅游
    NOIP2012疫情控制(二分答案+树上贪心)
    NOIP2017题解
    [SCOI2010]幸运数字(容斥+爆搜)
    [JSOI2008]Blue Mary的战役地图(二分+哈希)
    [湖南集训]谈笑风生(主席树)
    NOIP2016题解
  • 原文地址:https://www.cnblogs.com/jingxin1992/p/9066476.html
Copyright © 2011-2022 走看看