gpt4 book ai didi

ios - UIWebView 用户代理未正确设置自定义值

转载 作者:行者123 更新时间:2023-11-29 00:33:07 25 4
gpt4 key购买 nike

如果我们想改变用户代理的值

Mozilla/5.0 (iPhone; CPU iPhone OS 10_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Mobile/14B72

Mozilla/5.0 (iPad; CPU OS 10_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Mobile/14B72

即在iPhone应用上,我的应用需要设置iPad的User-Agent。

我的代码看起来像

class ViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
var userAgent:String = ""
override func viewDidLoad() {
super.viewDidLoad()
userAgent = self.webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")!

let range = userAgent.range(of: "iPhone")

if range != nil {
userAgent = userAgent.replacingCharacters(in: range!, with: "iPad")
userAgent = userAgent.replacingOccurrences(of: "iPhone", with: "")
}
userAgent = userAgent.replacingOccurrences(of: " ", with: " ")

UserDefaults.standard.register(defaults: ["UserAgent": userAgent])

}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

self.webView.loadRequest(URLRequest(url: URL(string: "http://www.google.com")!))
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let userAgent = request.allHTTPHeaderFields!["User-Agent"]
print("\(userAgent)")
return true
}

}

在上述情况下,User-Agent 未设置并保持默认值

如果我更改并在 viewDidLoad 中设置硬编码值,而不是像 iPad 的用户代理那样操作字符串的逻辑

UserDefaults.standard.register(defaults: ["UserAgent": “Mozilla/5.0 (iPad; CPU OS 10_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Mobile/14B72”])

那么它也不会更新。

但是如果我像这样硬编码

UserDefaults.standard.register(defaults: ["UserAgent": “MyValue”])

那么就设置好了

知道这里出了什么问题吗?

最佳答案

如果用js代码调用获取iOS浏览器用户代理值,此时iOS会创建并发送值。所以你不能在创建后更新用户代理。尝试手动编写所有用户代理,而不是像这样通过 javascript 调用:

    let manuelUserAgent = "Mozilla/5.0 (iPad; CPU OS 10_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Mobile/14B72"

let newUserAgent = "\(manuelUserAgent) YourOpt.Text"

UserDefaults.standard.register(defaults: ["UserAgent": newUserAgent])

关于ios - UIWebView 用户代理未正确设置自定义值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41260171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com