why

Now many apps will visit their home web pages, and then the brothers of the server will ask to set up the userAgent. Well, our promise is 馃槼.

implementation

Now that we’ve agreed, let’s see how this thing works. Let’s first look at how to get the userAgent thing.

UIWebView聽*webView聽=聽[[UIWebView聽alloc]聽init];

webUserAgent聽=聽[webView聽stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

Copy the code

So we get the userAgent of the system, and then we make ooxx changes to it and set it up.

[[NSUserDefaults聽standardUserDefaults]聽registerDefaults:@{@"UserAgent":聽webUserAgent}]

Copy the code

OK finish work ~! 馃榿 how naive, boy! You think this is the end of it? Not for a while, the backstage brothers came to tease you, said good UA how not set up successfully ah? 馃槒馃槒馃槒 ouch, the grass mud horse in my heart can not restrain the pentium ah! You need to call navigator.userAgent every time you use a WebView.

[webView聽stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

Copy the code

What the fuck is this hole? Ha ha ha, no matter how, is always overcome it, hair version! How naive again, boy! UserAgent setup failed! At this point, you can feel your hairline moving back 1 micron! After some hard thinking, I found that a third party library also set UA.

CFPreferencesSetAppValue(CFSTR("UserAgent"),聽(__bridge聽CFPropertyListRef聽_Nullable)(userAgent),聽CFSTR("com.apple.WebFoundation"))

Copy the code

What is this operation? Moreover, once this method is set, the above method cannot be changed. So what does this CFPreferencesSetAppValue thing do? Ahem, that’s what the official website says. Plist file programming API introduction well, in short, is to set up the configuration file. Finished! Okay, so there’s really nothing wrong with this, right? !

ps:

  1. Thanks to toutiao students, a tripartite library in the article is actually toutiao’s advertising SDK. The second way to set UA is also described by toutiao.
  2. From here you know Plist file programming. Get ready to read and write your next article.