LoginSignup
27
26

More than 5 years have passed since last update.

[Swift]UserAgentを設定する

Last updated at Posted at 2014-08-16

UIWebViewを使うときにUserAgentを設定する(Swift)

iPhoneのUIWebViewで見るときだけ違うものを表示させたいときに便利なのがUserAgent
これを設定することでサーバーサイドでUIWebViewでアクセスしていることを判定できます。

AppDelegate.swift
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
        // Override point for customization after application launch.

   //UserAgentを上書き
   let webView:UIWebView = UIWebView()
   webView.frame = CGRectZero
   let userAgent:String! = webView.stringByEvaluatingJavaScriptFromString("navigator.userAgent")
   let userAgentStr = "from UIWebView"
   let customUserAgent:String = userAgent.stringByAppendingString(userAgentStr)

   let dic:NSDictionary = ["UserAgent":customUserAgent]
   NSUserDefaults.standardUserDefaults().registerDefaults(dic)

   return true
}

今回"from UIWebView"となっているところに好きなUserAgentを設定すればokです。

27
26
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
27
26