- 環境
- Xcode Version 11.6
- 言語
- Objective-C
WKWebViewのユーザーエージェントの初期値を変更する
WKWebViewのユーザーエージェントの初期値を指定した名前に置き換える方法です。
#import <WebKit/WebKit.h>
// アプリのバージョン番号を取得
NSString* version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
// 設定するユーザーエージェントの名前
NSString* userAgent = [NSString stringWithFormat:@"MyApp Version=%@", version];
// ユーザーエージェントの初期値を変更する
NSDictionary* registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:userAgent, @"UserAgent", nil];
[NSUserDefaults.standardUserDefaults registerDefaults: registrationDictionary];
WKWebViewConfiguration* webConfig = [[WKWebViewConfiguration alloc] init];
WKWebView* webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:webConfig];
ユーザーエージェントは次のようになりました。
MyApp Version=1.0
WKWebViewのユーザーエージェントを変更する
WKWebViewのユーザーエージェントに指定した名前に置き換える方法です。
WKWebViewのcustomUserAgentにユーザーエージェントを設定します。
// アプリのバージョン番号を取得
NSString* version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
// 設定するユーザーエージェントの名前
NSString* userAgent = [NSString stringWithFormat:@"MyApp Version=%@", version];
// WKWebViewを作成する
WKWebViewConfiguration* webConfig = [[WKWebViewConfiguration alloc] init];
WKWebView* webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:webConfig];
// ユーザーエージェントを変更する
webView.customUserAgent = userAgent;
ユーザーエージェントは次のようになりました。
MyApp Version=1.0
customUserAgentで設定したユーザーエージェントは、NSUserDefaultsで設定したユーザーエージェントよりも優先されます。
WKWebViewのユーザーエージェントに追記する
WKWebViewのユーザーエージェントに指定した名前を追記する方法です。
WKWebViewConfigurationのapplicationNameForUserAgentに追記する名前を設定します。
// アプリのバージョン番号を取得
NSString* version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
// 追記するユーザーエージェントの名前
NSString* userAgent = [NSString stringWithFormat:@"MyApp Version=%@", version];
// WKWebViewを作成する
WKWebViewConfiguration* webConfig = [[WKWebViewConfiguration alloc] init];
webConfig.applicationNameForUserAgent = userAgent;
WKWebView* webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:webConfig];
ユーザーエージェントは次のようになりました。
Mozilla/5.0 (iPhone; CPU iPhone OS 13_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) MyApp Version=1.0
NSUserDefaultsやcustomUserAgentでユーザーエージェントを設定している場合、applicationNameForUserAgentの設定は適用されません。