WebView-修改userAgent用于网页端判断手机型号

//本文用于在userAgent后添加标识字段(dbios/版本号

前言

  • H5页面获得的UserAgent都是默认的UserAgent,而不是修改后的UserAgent,原因在于webView会将userAgent替换为默认。
  • 直接在加载webView处更改无效,故而我们在AppDelegate里面的- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions方法里修改默认的UserAgent。该方法能保证userAgent成功被修改。

正文


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    
    //修改userAgent,在后面添加字段
    //判断版本号
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
//    NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
//    NSLog(@"当前应用版本号码:%@",appCurVersionNum);
    
    NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSLog(@"当前应用软件版本:%@",appCurVersion);
    
    UIWebView * tempWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString * oldAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSString * newAgent = oldAgent;
    //此处在userAgent后添加加* dbios/版本号*
    if (![oldAgent hasSuffix:@" dbios"]) {
        newAgent = [oldAgent stringByAppendingString:[NSString stringWithFormat:@" dbios/%@",appCurVersion]];
    }
    NSLog(@"new agent :%@", newAgent);
    NSDictionary * dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    return YES;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 使用场景: 有个项目需求,要区分打开H5是在本地APP还是在手机浏览器,前端伙伴说需要配合修改默认的UserAge...
    千寻_544f阅读 5,621评论 0 4
  • 项目中有需求要修改网页的代理UserAgent:H5页面需要判断当前页面是在微信还是在原生的APP中。刚开始一筹莫...
    Misaki_yuyi阅读 9,289评论 7 20
  • 非原创,收集,整理,觉得有用就罗列下为避免下次犯迷糊。 IOS 中的 AppDelegate.m/h 文件是很重要...
    西蜀阅读 541评论 0 0
  • 概述 在多数移动应用中任何时候都只能有一个应用程序处于活跃状态,如果其他应用此刻发生了一些用户感兴趣的那么通过通知...
    莫离_焱阅读 6,611评论 1 8
  • 昨日深圳磨房百公里,官方开始时间为六点,但从三点就开始放行。小编是三点半到的现场,已经人山人海,四点开始从深圳湾主...
    枭熊阅读 844评论 0 1