iOS:WKWebView设置UserAgent

本文介绍了在iOS开发中,为了使前端H5能够识别App内部还是浏览器环境,如何使用WKWebView自定义UserAgent。相较于UIWebView的内存问题,WKWebView成为更好的选择。关键步骤包括设置customUserAgent,确保这一行代码的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

iOS开发中,前端H5想获知H5页面是在App内部还是在其他浏览器被打开,则需要客户端配合修改默认的UserAgent, 以便区分。在iOS8之前一直用的都是UIWebView,但是在iOS9出了一个WKWebView,对比起来前者UIWebview就具有严重的内存问题,UIWebView会被慢慢淘汰。

WKWebView修改UserAgent代码如下:

- (void)configWebViewUserAgent {
  WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero];

  // 获取当前UserAgent, 并对其进行修改
  [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id userAgent, NSError * _Nullable error) {
    if (![oldAgent isKindOfClass:[NSString class]]) {
        // 为了避免没有获取到oldAgent,所以设置一个默认的userAgent
        // Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
        oldAgent = [NSString stringWithFormat:@"Mozilla/5.0 (%@; CPU iPhone OS %@ like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148", [[UIDevice currentDevice] model], [[[UIDevice currentDevice] systemVersion] stringByReplacingOccurrencesOfString:@"." withString:@"_"]];
      }
      //自定义user-agent
      NSString *newAgent = oldAgent;
      if ([oldAgent rangeOfString:@"iOS_CFZQ_LEZHUAN"].location == NSNotFound) {
          newAgent = [NSString stringWithFormat:@"%@;  iOS_CFZQ_LEZHUAN_%@",oldAgent,[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
       }
            
       // 一定要设置customUserAgent,否则执行navigator.userAgent拿不到oldAgent
       webView.customUserAgent = newAgent;
       NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
       [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
       [[NSUserDefaults standardUserDefaults] synchronize];
     }];
  }];
}

切记:一定要设置customUserAgent,这行代码一定要写上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值