iOS中修改WebView默认的User Agent

本文介绍在iOS应用中如何修改UIWebView的默认UserAgent,并提供两种有效解决方案:通过加载请求数据到UIWebView或修改默认UserAgent。

iOS中修改WebView默认的User Agent

2014-05-28 | 评论

今天遇到一个需求,因某些原因,需要在webview默认的user agent中增加一些自定义的东西。经测试发现,webview的-webView:shouldStartLoadWithRequest:navigationType:方法中修改request的UA或者重新load修改UA过的NSMutableURLRequest都不行,webview会替换成默认的UA,类似

1
 Mozilla/5.0 (iPod touch; CPU iPhone OS 7_1_1 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D201

两个解决方案:

方案1:在-webView:shouldStartLoadWithRequest:navigationType:方法中同步加载到request的data,然后使用UIWebView的-loadData:MIMEType:textEncodingName:baseURL:方法加载data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (...) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSHTTPURLResponse *response = nil;
            NSError *error = nil;
            NSData *data = [NSURLConnection sendSynchronousRequest:request
                                                 returningResponse:&response
                                                             error:&error];
            if (error) {
                // ...
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.webView loadData:data
                              MIMEType:response.MIMEType
                      textEncodingName:response.textEncodingName
                               baseURL:request.URL];
            });
        });
        return NO;
    }
    return YES;
}

方案2:在AppDelegate的-applicationDidFinishLaunching:方法中增加如下代码,修改默认User Agent

1
2
3
4
5
6
7
8
9
10
11
@autoreleasepool {
    UIWebView* tempWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString* userAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSString *ua = [NSString stringWithFormat:@"%@\\%@",
                    userAgent,
                    @"custom string"];
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent" : ua, @"User-Agent" : ua}];
#if !__has_feature(objc_arc)
    [tempWebView release];
#endif
}

这种方式会直接修改App默认的UA,推荐使用这种方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值