iOS - Modify UserAgent (WKWebView & UIWebView)

Let's talk about the special character 'UserAgent' today, because we have a judgment in the background that if 'UserAgent' contains the character 'iPad', then it is 1, otherwise it is 0.

After 'iPad' is upgraded to 'iPadOS 13', the content of UserAgent has been changed, and the 'iPad' in the previous string has been changed to 'Macintosh', so it is natural that some functions of the customer cannot be used. Let's briefly talk about this problem below. Well, of course when I write this blog, I believe that my customers are already flying freely in the APP~ I wish you happiness~ 

First, introduce the 'UserAgent' 

User Agent (User Agent), referred to as UA, is a special string header that enables the server to identify the operating system and version, CPU type, browser and version, browser rendering engine, browser language, and browser plug-in used by the client. wait.

So you can understand it as a special character. There are many attributes in this character to represent its identity. Guess what is specific about iOS?

 

 

Second, I just took a screenshot of the UserAgent of iPad 12 and 13 to understand. From the content, Apple really wants to play the iPad as a Mac.

Before the upgrade, the system was iPad OS 12.4.1. 

After upgrading 'Macintosh'.

 

Third, you need to know that 'UserAgent' can be changed manually. WkWebView and UIWebView are different. Write down both methods below, and remind you not to use 'UIWebView' again.

    WKWebView *WKWeb = [[WKWebView alloc] init];
    //一般的时候,我们可以通过JS 调用到userAgent,然后增加一些内容后赋值。
    [WKWeb evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        NSString *oldUserAgent = result;
        NSString *newUserAgent = [NSString stringWithFormat:@"%@ %@",oldUserAgent,@"TheNewWordForUserAgent"];
        webView.myWKWebView.customUserAgent = newUserAgent;
    }];
    //二班的小伙伴,不需要以前的内容那么直接改。
    WKWeb.customUserAgent = @"这个属性可以直接调用,调用直接改比UIWebView 方便多了";
   //了解一下就可以
   UIWebView *UIWeb = [[UIWebView alloc] init];
   NSString *oldAgent = [UIWeb stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
   NSString *newAgent = [NSString stringWithFormat:@"%@ %@",oldAgent,@"TheNewWordForUserAgent"];
    
   NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
   [[NSUserDefaults standardUserDefaults] registerDefaults: dic];
   [[NSUserDefaults standardUserDefaults] synchronize];

Well, whether to change or not depends on the needs, and whether to do it or not depends on yourself.

Thank you for watching, and thank you for applying what you have learned!

 

 

Guess you like

Origin blog.csdn.net/siwen1990/article/details/102069410