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行で設定できます
// 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!!";
}