1)什么是User Agent?
1. 用户代理 User Agent,是指浏览器,它的信息包括硬件平台、 系统软件、应用软件和用户个人偏好。
2. 早的时候有一个浏览器叫NCSA Mosaic,把自己标称为 NCSA_Mosaic/2.0 (Windows 3.1),它支持文字显示的同时还支持图片,于是Web开始好玩起来。
3. 通过浏览器navigator.userAgent,可以获得用户的UserAgent。
4. UserAgent简称UA,可以用作一个用户的真实访问,一般的Web统计流量也会针对UA信息去统计浏览器占比,移动占比等等。
复制代码
2)怎么设置两种方法
1.直接在app delegate 里面设置(这种方法比较简单,其中具体的参数自己选择性的设置)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//修改app默认UA
UIWebView* tempWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString* userAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
// NSLog(@"------%@",userAgent);
NSString *executableFile = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleExecutableKey];
NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];
NSString *ua = [NSString stringWithFormat:@"%@ %@/%@", userAgent, executableFile,version];
// NSLog(@"------%@",ua);
[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent" : ua, @"User-Agent" : ua}];
return YES; }
2.第二种方法
在webView:shouldStartLoadWithRequest:navigationType:方法中同步加载到request的data,然后使用UIWebView的-loadData:MIMEType:textEncodingName:baseURL:方法加载data
- (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;}
复制代码
3)测试是否成功(打印对应的UA) //在Safari中打开文章中的文档 - (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType { NSLog(@"ua=======%@",[request valueForHTTPHeaderField:@"User-Agent" ]); //判断是否是单击 if (navigationType == UIWebViewNavigationTypeLinkClicked) {
NSURL *url = [request URL]; [[UIApplication sharedApplication]openURL:url]; return NO; } return YES;}
1867

被折叠的 条评论
为什么被折叠?



