如何防止WKWebView的“用户代理”标题发生更改?

时间:2021-07-02 09:59:57
    let url =  NSURL(string:"http://www.examplepage.com/“)
            let Request = NSMutableURLRequest(URL: url!)


            Request.setValue("Custom-Agent", forHTTPHeaderField: "User-Agent")

            let task1 = NSURLSession.sharedSession().dataTaskWithRequest(Request){ data, response, error in

                let contentPage =  NSString(data: data!, encoding: NSUTF8StringEncoding)
                self.webView!.loadHTMLString(contentPage! as String, baseURL: url)

            }
            task1.resume()

I’ve used the following code to set the “User Agent” header of a WKWebView.

我使用了以下代码来设置WKWebView的“用户代理”头。

It works well when the app first loaded, but only after a button is clicked into the link the “User-Agent” changes.

当应用程序第一次加载时,它运行得很好,但是只有当一个按钮被点击到链接中,“用户代理”才会改变。

How can I prevent the "User-Agent" from changing?

如何防止“用户代理”发生更改?

2 个解决方案

#1


1  

  1. For iOS 9, use the customUserAgent property on the web view.

    对于iOS 9,使用web视图上的customUserAgent属性。

  2. For iOS 8 and earlier, do this instead:

    对于iOS 8和更早的版本,请这样做:

    NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent" : "BlahBlahBlah"])

    NSUserDefaults.standardUserDefaults()。registerDefaults([“UserAgent”:“BlahBlahBlah”])

#2


0  

I've managed to do it. Here is the solution!

我已经做到了。这是解决方案!

The ViewController:

ViewController:

override func viewDidAppear(animated: Bool) {

        let url = NSURL(string:"http://www.examplepage.com/")!
        webView!.loadRequest(NSURLRequest(URL: url))
        webView!.allowsBackForwardNavigationGestures = true     
    }

The AppDelegate:

在AppDelegate:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent": “YourUserAgent”])

    return true
    }

#1


1  

  1. For iOS 9, use the customUserAgent property on the web view.

    对于iOS 9,使用web视图上的customUserAgent属性。

  2. For iOS 8 and earlier, do this instead:

    对于iOS 8和更早的版本,请这样做:

    NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent" : "BlahBlahBlah"])

    NSUserDefaults.standardUserDefaults()。registerDefaults([“UserAgent”:“BlahBlahBlah”])

#2


0  

I've managed to do it. Here is the solution!

我已经做到了。这是解决方案!

The ViewController:

ViewController:

override func viewDidAppear(animated: Bool) {

        let url = NSURL(string:"http://www.examplepage.com/")!
        webView!.loadRequest(NSURLRequest(URL: url))
        webView!.allowsBackForwardNavigationGestures = true     
    }

The AppDelegate:

在AppDelegate:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent": “YourUserAgent”])

    return true
    }