Change User Agent in UIWebView

前端 未结 14 1977
孤城傲影
孤城傲影 2020-11-22 17:03

I have a business need to be able to customize the UserAgent for an embedded UIWebView. (For instance, I\'d like the server to respond differently if, say, a user is using

14条回答
  •  眼角桃花
    2020-11-22 18:00

    Very simple in Swift. Just place the following into your App Delegate.

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

    If you want to append to the existing agent string then:

    let userAgent = UIWebView().stringByEvaluatingJavaScript(from: "navigator.userAgent")! + " Custom Agent"
    UserDefaults.standard.register(defaults: ["UserAgent" : userAgent])
    

    Note: You may will need to uninstall and reinstall the App to avoid appending to the existing agent string.

提交回复
热议问题