123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- //
- // WKWebView+UserAgent.m
- // Starbuds
- //
- // Created by 翟玉磊 on 2020/5/25.
- // Copyright © 2020 翟玉磊. All rights reserved.
- //
- #import "WKWebView+UserAgent.h"
- @implementation WKWebView (UserAgent)
- /// 设置自定义的Agent 和H5交互
- /// 一定要在初始化添加到父view后在调用才会生效
- - (void)setupCustomUserAgent {
- if (@available(iOS 12.0, *)){
- //由于iOS12的UA改为异步,所以不管在js还是客户端第一次加载都获取不到,所以此时需要先设置好再去获取(1、如下设置;2、先在AppDelegate中设置到本地)
- NSString *language = [NSString kcSeverLanguage];
- NSString *userAgent = [self valueForKey:@"applicationNameForUserAgent"];
- NSString *customUserAgent = [NSString stringWithFormat:@"%@/%@/lang:%@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"], APP_VERSION, language];
- NSString *newUserAgent = [NSString stringWithFormat:@"%@ %@", userAgent, customUserAgent];
- [self setValue:newUserAgent forKey:@"applicationNameForUserAgent"];
- }
- [self evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
- NSString *userAgent = result;
- NSString *language = [NSString kcSeverLanguage];
- NSString *customUserAgent = [NSString stringWithFormat:@"%@/%@/lang:%@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"], APP_VERSION, language];
- NSLog(@"userAgent:%@", userAgent);
- if ([userAgent rangeOfString:customUserAgent].location != NSNotFound) {
- return ;
- }
- NSString *newUserAgent = [userAgent stringByAppendingString:customUserAgent];
- // NSLog(@"%@>>>%@>>>>>",userAgent,newUserAgent);
- NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent,@"UserAgent", nil];
- [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
- [[NSUserDefaults standardUserDefaults] synchronize];
- //不添加以下代码则只是在本地更改UA,网页并未同步更改
- if (@available(iOS 9.0, *)) {
- [self setCustomUserAgent:newUserAgent];
- } else {
- [self setValue:newUserAgent forKey:@"applicationNameForUserAgent"];
- }
- }];
- }
- @end
|