LoginSignup
4
4

More than 5 years have passed since last update.

UserAgentの設定をとても簡単にカスタムする方法

Last updated at Posted at 2016-09-01

2016/0901 この記事は環境:Xcode7.3.1です。

目的

WebViewで表示する際サーバにRequestするUser-Agentヘッダーにアプリバージョンを付与させたい。

AppDelegateを編集する(UIWebView)

WebViewを使って通信を行う前に設定をしないと反映されないので、AppDelegateの didFinishLaunchingWithOptionsに記述します。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

// デフォルトのUserAgentを取得するために、サイズゾロのUIWebViewインスタンスを生成
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];

    // デフォルトのUserAgentを取得
    NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

    NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];

    // デフォルトのUserAgent文字列後尾にアプリバージョンを追加した文字列を作成
    NSString *customUserAgent = [userAgent stringByAppendingString:[NSString stringWithFormat:@" AppVersion/%@",appVersion]];

    // UserAgentをkyeとし,customUserAgentをvalueとした辞書型変数を作成
    NSDictionary *userAgentDict = [[NSDictionary alloc] initWithObjectsAndKeys:customUserAgent, @"UserAgent", nil];

    // ユーザーデフォルトにカスタムUserAgentを設定
    [[NSUserDefaults standardUserDefaults] registerDefaults:userAgentDict];

 }

デフォルトUserAgentを使用しない場合の記述はとても少なく、上記didFinishLaunchingWithOptionsにおいて2行で設定できます :smile:


   // UserAgentをkyeとし,customUserAgentをvalueとした辞書型変数を作成
    NSDictionary *userAgentDict = [[NSDictionary alloc] initWithObjectsAndKeys:@"InsertCustomUserAgent!!", @"UserAgent", nil];

    // ユーザーデフォルトにカスタムUserAgentを設定
    [[NSUserDefaults standardUserDefaults] registerDefaults:userAgentDict];

AppDelegateを編集する(WKWebView)

同じくWebViewを使って通信を行う前に設定をしないと反映されないので、AppDelegateの didFinishLaunchingWithOptionsに記述します。WKWebViewはUserAgentプロパティが用意されているので代入するだけで設定可能です。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    WKWebView *webView = [[WKWebView alloc] init];
    webView.customUserAgent = @"InsertCustomUserAgent!!";
}
4
4
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
4
4