公司的前端要給項目的webview加一個區分,用來區別是iOS端訪問、android訪問還是在瀏覽器訪問的,說是要加一個User Agent ,前端根據不同信息做適配,和我說來一頭霧水,後來經過開發同事的指導和在網上查閱資料,才有了點頭緒,在這裡和大家分享一下。 一、獲取UserAgent 最終得到 ...
公司的前端要給項目的webview加一個區分,用來區別是iOS端訪問、android訪問還是在瀏覽器訪問的,說是要加一個User Agent ,前端根據不同信息做適配,和我說來一頭霧水,後來經過開發同事的指導和在網上查閱資料,才有了點頭緒,在這裡和大家分享一下。
一、獲取UserAgent
UIWebView方式:
UIWebView* tempWebView = [[UIWebView alloc] initWithFrame:CGRectZero]; NSString* userAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"]; NSLog(@"UIWebView預設的userAgent = %@", userAgent);
預設UserAgent輸出:
UIWebView預設的userAgent = Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E304
二、修改UserAgent
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { UIWebView* tempWebView = [[UIWebView alloc] initWithFrame:CGRectZero]; NSString* userAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"]; NSLog(@"UIWebView預設的userAgent = %@", userAgent); NSString *versionsss = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];; NSString *ua = [NSString stringWithFormat:@"%@/XYWY_YIMAI/iOS/%@", userAgent, versionsss];//自定義需要拼接的字元串 [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent" : ua, @"User-Agent" : ua}]; }
獲取UserAgent輸出:
NSMutableURLRequest *request = ..... /** 獲取系統的UA */ NSString *sysUA = request.allHTTPHeaderFields[@"User-Agent"];
最終得到修改後的:
Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E304/XYWY_YIMAI/iOS/5.5