1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

アプリ経由でのWebサイトアクセスを識別するためにユーザエージェントを加工する【Swift3.0】

Last updated at Posted at 2016-11-28

GoogleAnalyticsなどで、アプリ経由でのWebサイトアクセスを識別するためにユーザエージェントを加工する

「デフォルトのユーザエージェント」 + 「"AppName/"{アプリバージョン}」

    // swift 3.0

    func setAppUserAgent() {
        
        // ダミーのwebviewからデフォルトユーザエージェントを取得
        let webViewDummy = UIWebView(frame:CGRect.zero)
        let useragent:String = webViewDummy.stringByEvaluatingJavaScript(from: "navigator.userAgent")!
        
        // デフォルトのユーザエージェントにアプリ名+バージョン情報を付加
        let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
        let wkStr = " AppName/" + version
        let addedUserAgent = useragent + wkStr
        let agentDict = ["UserAgent":addedUserAgent]

        UserDefaults.standard.register(defaults: agentDict)
    }

    // ex.
    // Mozilla/5.0 (iPhone; CPU iPhone OS 10_0 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Mobile/14A345 AppName/1.0
起動時にコール
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        setAppUserAgent() 
        
        return true
    }
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?