0xS*_*ina 35 cocoa-touch objective-c uiwebview ios
如何在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;
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*man 89
在应用启动时运行此代码一次,更改"UserAgent"默认值:
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"Your user agent", @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
Run Code Online (Sandbox Code Playgroud)
编辑:我已经使用了这个非常成功,但想要添加其他细节.要获取用户代理,您可以启用"开发人员"菜单,设置用户代理,然后连接到此站点以便为您打印出来:WhatsMyAgent.同样,您可以使用任何类型的移动设备进行连接,也可以通过这种方式进行连接.顺便说一句,这在iOS7 +中仍然可以正常工作
归档时间: |
|
查看次数: |
27501 次 |
最近记录: |