UIWebView iOS5更改用户代理

37

我怎样才能在iOS 5中更改UIWebView的用户代理?

到目前为止我所做的事情: 使用委托回调函数,拦截NSURLRequest,创建一个新的URL请求并设置其用户代理为我想要的任何内容,然后下载数据并使用"loadData:MIMEType:..."重新加载UIWebView。

问题: 这会导致无限递归,其中我加载数据,调用委托回调函数,进而又调用了委托...

这是委托方法:

- (BOOL)webView:(UIWebView *)aWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {



    dispatch_async(kBgQueue, ^{
        NSURLResponse *response = nil;
        NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[request URL]];
        NSDictionary *headers = [NSDictionary dictionaryWithObject:
                                 @"custom_test_agent" forKey:@"User-Agent"];
        [newRequest setAllHTTPHeaderFields:headers];
        [self setCurrentReqest:newRequest];
        NSData *data = [NSURLConnection sendSynchronousRequest:newRequest 
                                             returningResponse:&response 
                                                         error:nil];
        dispatch_sync(dispatch_get_main_queue(), ^{
            [webView loadData:data 
                     MIMEType:[response MIMEType] 
             textEncodingName:[response textEncodingName] 
                      baseURL:[request URL]];
        });
    });

    return YES;
}

请分享setCurrentReqest方法。 - sanjeev sharma
可能是在UIWebView中更改用户代理的重复问题。 - Cœur
3个回答

89

当你的应用启动时,运行以下代码一次即可更改"UserAgent"的默认值:

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"Your user agent", @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];  

编辑:我已经使用这个方法并且非常成功,但是想要添加一些细节。如果你想得到一个用户代理,你可以启用"开发者"菜单,设置用户代理,然后连接到这个网站来打印出来:WhatsMyAgent。同样地,你也可以使用任何类型的移动设备来连接,并以此方式获取它。顺便说一句,这在iOS7+上仍然可以正常工作。


2
非常好用!我必须将它设置在我的PhoneGap应用程序的AppDelegate.mm文件中的+(void)initialize{}方法中。 - Aki
3
这个函数运行得非常完美: + (void)initialize { NSDictionary *dictionary = @{ @"UserAgent" : @"Safari iOS 5.1 - iPhone"}; [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
}
- David H
它会将这个新的用户代理字符串附加到默认的用户代理字符串中吗?还是会覆盖它? - Adil Malik
@DavidH,你的版本解决了我的部分问题。感谢您包含用户代理字符串!您从哪里得到的?我想知道是否有不同的字符串可以解决我的剩余问题。 - JohnK
@Adil,请看这里获取更多信息。我之前用过的方法对我有用,是从StackOverflow上的某篇帖子中得到的:http://enterpriseios.com/wiki/UserAgent - David H
显示剩余4条评论

1
在Swift中,使用以下代码设置UserAgent:`UserAgent`。
func setUserAgent(){

    var userAgent = NSDictionary(objectsAndKeys:  "YourUserAgentName","UserAgent")

    NSUserDefaults.standardUserDefaults().registerDefaults(userAgent as [NSObject : AnyObject])

}

Use this to test,

println(WebView.stringByEvaluatingJavaScriptFromString("navigator.userAgent"));

0
当您发送消息[aWebView loadData:MIMEType:textEncodingName:baseURL:]时,aWebView shouldStartLoadWithRequest:将再次被调用,然后再次被调用 - 这就是为什么您会得到无限递归的原因。
您应该限制调用dispatch_async()块的方式,例如使用一些常规URL:
- (BOOL)webView:(UIWebView *)aWebView shouldStartLoadWithRequest:(NSURLRequest *)request 
        navigationType:(UIWebViewNavigationType)navigationType {


    if ([[[request URL] absoluteString] isEqualToString:@"http://yourdomain.com/?local=true"]) {
        return YES;
    }


    ...

    dispatch_async(...
            [aWebView loadData:data 
                      MIMEType:[response MIMEType] 
              textEncodingName:[response textEncodingName] 
                       baseURL:[NSURL URLWithString:@"http://yourdomain.com/?local=true"]];

    );
    return NO;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接