LoginSignup
2
2

More than 5 years have passed since last update.

UIWebViewにUserAgentをつけて表示を変えたい…!

Posted at

Apple does not support it and add it as Default, so we have to declare it in AppDelegate, which means we are supposed to call following function before creating WebView

Development Environment

  • OS X El Captain 10.11.2
  • Xcode Version 8.0

Language

Swift 3.0

Step

1 Add below code in AppDelegate.swift

AppDelegate.swift
private func setupCustomUserAgent() {
        //UserAgentを上書き
        let webView:UIWebView = UIWebView()
        webView.frame = CGRect.zero
        let userAgent:String! = webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")
        let userAgentStr = "QiitaLaw"
        let customUserAgent:String = userAgent.appending(userAgentStr)
        let dic:NSDictionary = ["UserAgent":customUserAgent]
        UserDefaults.standard.register(defaults: dic as! [String : AnyObject])
    }

2 Call that function in following

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        setupCustomUserAgent()
        return true
    }

3 Done

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2