UA在項目中的應用
給項目的webview或項目中的接口請求加一個區分,用來區別是iOS端訪問、android訪問還是在瀏覽器訪問的,這時需要添加User Agent (http請求 header中的一個參數)
1)什么是User Agent? 1. 用戶代理 User Agent,是指瀏覽器,它的信息包括硬件平台、 系統軟件、應用軟件和用戶個人偏好。 2. 早的時候有一個瀏覽器叫NCSA Mosaic,把自己標稱為 NCSA_Mosaic/2.0 (Windows 3.1),它支持文字顯示的同時還支持圖片,於是Web開始好玩起來。 3. 通過瀏覽器navigator.userAgent,可以獲得用戶的UserAgent。 4. UserAgent簡稱UA,可以用作一個用戶的真實訪問,一般的Web統計流量也會針對UA信息去統計瀏覽器占比,移動占比等等。
2)webview全局的設置兩種方法:
//1.直接在app delegate 里面設置(這種方法比較簡單,其中具體的參數自己選擇性的設置) - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //修改app默認UA UIWebView* tempWebView = [[UIWebView alloc] initWithFrame:CGRectZero]; NSString* userAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"]; // NSLog(@"------%@",userAgent); NSString *executableFile = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleExecutableKey]; NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey]; NSString *ua = [NSString stringWithFormat:@"%@ %@/%@", userAgent, executableFile,version]; // NSLog(@"------%@",ua); [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent" : ua, @"User-Agent" : ua}]; return YES; } // 2.第二種方法 //在webView:shouldStartLoadWithRequest:navigationType:方法中同步加載到request的data,然后使用UIWebView的-loadData:MIMEType:textEncodingName:baseURL:方法加載data - (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if (...) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSHTTPURLResponse *response = nil; NSError *error = nil; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (error) { // ... } dispatch_async(dispatch_get_main_queue(), ^{ [self.webView loadData:data MIMEType:response.MIMEType textEncodingName:response.textEncodingName baseURL:request.URL]; }); }); return NO; } return YES; }
3) 一般的網絡請求在request
// AFN中 在 AFHTTPRequestSerializer 類中 //調用- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(NSString*)field; 給請求頭設置參數 @"User-Agent" 的值
