当前位置:首页 > 操作系统 > Ios

iOS 修改UIWebView的UserAgent

iOS和H5交互的时候,H5需要用userAgent带一些参数,需要我们修改默认的UserAgent为自定义的。

首先,给大家普及一下userAgent的历史,点击UserAgent查看。

网上搜了好多资料。没有一个方式是好用的,总结起来,以下2个方法都不好用:

1 ,直接设置request的header里面的userAgent

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

[request addValue:@"Jiecao/2.4.7" forHTTPHeaderField:@"user-agent"];

[self.webView loadRequest:request];

2,在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是只读属性,所以失败。第二个方法,修改的是全局的UserAgent设置,[NSUserDefault stangarUserDefault]是一个单例,修改完到下一次调用之前,会被默认值覆盖。(自己猜的)

所以,正确的修改方式是在loadRequest之前去修改这个全局UserAgent值。

NSString *customUserAgent = [NSString stringWithFormat:@" %@/%@/%@", @"wt", @"iPhone", @"1.0.0"];
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":customUserAgent}];
    NSURL *url = [NSURL URLWithString:self.requestUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:10.f];
    [self.webHolder loadRequest:request];

最后补充一句,用的是EasyJS做交互。

 

原文:http://www.cnblogs.com/6duxz/p/5403847.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!