iOS和H5交互的時候,H5需要用userAgent帶一些參數,需要我們修改默認的UserAgent為自定義的。
首先,給大家普及一下userAgent的歷史,點擊UserAgent查看。
1 在Appdelegate里面register一個新的UserAgent
//get the original user-agent of webview UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero]; NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"]; NSLog(@"old agent :%@", oldAgent); //add my info to the new agent NSString *newAgent = [oldAgent stringByAppendingString:@" Jiecao/2.4.7 ch_appstore"]; NSLog(@"new agent :%@", newAgent); //regist the new agent NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
答案:該方法修改的是全局的UserAgent設置,[NSUserDefault stangarUserDefault]是一個單例,webView請求的時候就會從該單例中取值。注意,該方法只會修改webView的userAgent,其他的http請求的userAgent不會受影響。
最后補充一句,用的是EasyJS做交互。