LoginSignup
8
8

More than 5 years have passed since last update.

UIWebViewにCustomUserAgentを設定する

Posted at

アプリ版だけCSSの表示を変えたいとか、これを出したくないとかいう場面はあると思います。
そこで、UserAgentを使って振り分ける方法を試してみました。

WebViewのUAを取るとブラウザ(Safari)と判別は出来そうですが、
今回はカスタムのUAを新たに設定する方法を試します。
(Twitter、FacebookもカスタムUAを設定しているらしいので)
ブラウザかWebViewか、どちらで開かれたのかを判別するには - console.lealog();

iOS

UIWebViewのインスタンス生成後にUAの設定をしようとしても反映されないので、
実際に使うWebViewを生成する前に設定処理を書きます。(初回起動時に設定する)

AppDelegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    setupCustomUserAgent()
    return true
}

private func setupCustomUserAgent() {
    // サイズ0のUIWebViewのインスタンスを生成
    let webView = UIWebView(frame: CGRectZero)

    // デフォルトのUAから、mapを使い新たな文字列をappendしたカスタムUAを得る
    if let customUserAgent = webView.stringByEvaluatingJavaScriptFromString("navigator.userAgent").map({ "\($0) webview" }) {
        // UAの再設定
        NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent": customUserAgent])
    }  
} 

JavaScript

UAを判定する

var Utils = (function () {
    function Utils() {}

    var ua = navigator.userAgent.toLowerCase();

    Utils.isIOS = function () {
        return /ip(hone|od|ad)/.test(ua);
    };
    Utils.isAndroid = function () {
        return /android/.test(ua);
    };
    Utils.isWebView = function () { 
        return /webview/.test(ua); 
    };
    Utils.isPC = function () {
        return this.isIOS() === false && this.isAndroid() === false;
    };
    Utils.isSP = function () {
        return this.isPC() === false;
    };    
    return Utils;
})();        

if (Utils.isWebView()) {
    console.log("webView.")
} else if (Utils.isIOS) {
    console.log("iOS.")    
} else {
    console.log("other.")
}
8
8
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
8
8