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做交互。