UIWebView iOS5更改用户代理 [英] UIWebView iOS5 changing user-agent

查看:130
本文介绍了UIWebView iOS5更改用户代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在iOS 5中更改UIWebView的用户代理?

How can I change the user-agent of UIWebView in iOS 5?

我到目前为止做了什么:
使用委托回调,拦截NSURLRequest,创建一个新的url请求并设置它的用户代理作为任何我想要的,然后下载数据,并重新加载UIWebView与loadData:MIMEType:....。

What I have done so far: Using the delegate call back, intercept the NSURLRequest, create a new url request and set it's user-agent as whatever I want, then download the data and reload the UIWebView with "loadData:MIMEType:....".

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

Problem: This causes infinite recursion, where I load the data, which calls the delegate back, which intern calls the delegate....

这里是委托方法:

- (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;
}


推荐答案

更改UserAgent应用程序启动时运行此代码一次:

Change the "UserAgent" default value by running this code once when your app starts:

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

编辑:我使用这个非常成功,但想添加更多的细节。要获取用户代理,您可以启用开发人员菜单,设置用户代理,然后连接到此网站,以便为您打印出来: WhatsMyAgent 。同样,你可以使用任何类型的移动设备连接,并得到它的方式。 BTW这仍然工作很好在iOS7 +

I have used this with great success, but want to add additional details. To get a user agent, you can enable the "Developer" menu, set the user agent, and then connect to this site to get it printed out for you: WhatsMyAgent. Likewise you can connect using any kind of mobile device, and get it that way too. BTW this is still working just fine in iOS7+

这篇关于UIWebView iOS5更改用户代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆