web判断ios android,通过UserAgent判断是否为手机(浏览器,Android,IOS)

在项目中嵌入了一个修改密码的界面 浏览器中直接打开界面大致是这样:

0d1588e5598f

21F97C68-4A06-4E3C-847A-D57D3A27619A.png

在项目中我们有导航栏 上面的一部分“重置密码”这些字不需要显示出来

界面大致这样:

0d1588e5598f

26313D7B-460F-4D2B-B09B-0B8797153A80.png

这个时候我们可以使用userAgent

在请求头中修改给字段,当请求响应这个界面是根据这一个字段判断是不是移动设备

代码如下:

import "ForgotPasswordViewController.h"

@interface ForgotPasswordViewController ()

{

UIWebView *_webview;

}

@end

@implementation ForgotPasswordViewController

(instancetype)init{

self = [super init];

if (self) {

UIWebView *webview = [[UIWebView alloc] initWithFrame:CGRectZero];

NSString *oldAgent = [webview stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

NSLog(@"old agent :%@", oldAgent);

NSString *newAgent = [oldAgent stringByAppendingString:@"约定好的字段这里就以abcd表示"];

NSLog(@"new agent :%@", newAgent);

NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];

[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

}

return self;

}

(void)viewDidLoad {

[super viewDidLoad];

self.view.backgroundColor = [UIColor whiteColor];

_webview = [[UIWebView alloc] initWithFrame:self.view.bounds];

_webview.scalesPageToFit = YES;

_webview.scrollView.scrollEnabled = NO;

_webview.delegate =self;

[self.view addSubview:_webview];

NSURL *url = [NSURL URLWithString:

[NSString stringWithFormat:@"网页地址"]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request addValue:@"约定好的字段这里就以abcd表示"forHTTPHeaderField:@"UserAgent"];

[_webview loadRequest:request];

NSString *oldAgent = [_webview stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

NSLog(@"old agent :%@", oldAgent);

}

(void)webViewDidFinishLoad:(UIWebView *)webView

{

//导航栏中显示网页的标题

self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];

}

(void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}