UA access

Get it from UIWebView

UIWebView().stringByEvaluatingJavaScript(from: "navigator.userAgent")
Copy the code

Asynchronously obtained from WKWebView

webView.evaluateJavaScript("navigator.userAgent") { (result, error) in
    iferror ! =nil {
        print("error = \(error)")}else {
        print("result = \(result)")}}Copy the code

It is said on the Internet that WKWebView may fail to obtain UA, but I did not encounter it.

WK executes JS methods asynchronously. If WK is released prematurely, an error will be reported.

WKWebView.init().evaluateJavaScript("navigator.userAgent") { (result, error) in
    iferror ! =nil {
        print("error = \(error)")}else {
        print("result = \(result)")}}Copy the code
<! ErrorDomain =WKErrorDomain Code=3"The WKWebView was invalidated" UserInfo={NSLocalizedDescription=The WKWebView was invalidated}
Copy the code

UA set

Global UA Settings

UserDefaults.standard.register(defaults: ["UserAgent": "I'm the new UA"])
Copy the code

Use simple line of code is set, the best in the application of didFinishLaunchingWithOptions calls, can cooperate for UA set for their new UA.

Simple no, unfortunately iOS 12 after the problem !!!!

Scope of application

  • UIWebView && iOS 9+
  • WKWebView && iOS [9, 12)

UA Settings for WKWebView after iOS 12

The key code

/** @abstract The custom user agent string or nil if no custom user agent string has been set.
*/
@available(iOS 9.0, *)
open var customUserAgent: String?
Copy the code

use

webView.customUserAgent = "Custom UA"
Copy the code

Note Setting customUserAgent needs to be assigned before loadRequest and evaluateJavaScript.