第一次做和H5交互的项目,和大家分享一下经验,不喜勿喷!
以前做的项目,仅仅只是用UIWebView加载一个完整的URL或者一个H5的代码,这次做的项目,需要点击H5页面上的的按钮,跳转到iOS原生的界面!
UIWebView三种加载方式,相信大家都了如指掌了!
webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, HR_SCREEN_WIDTH, HR_SCREEN_HEIGHT)];
_webView.delegate = self;
_webView.backgroundColor = HR_BG_COLOR;
_webView.scalesPageToFit = YES;
_webView.scrollView.showsHorizontalScrollIndicator = NO;
_webView.scrollView.bounces = NO;
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@Index.html",H5_BASE_URL]]]];
[self.view addSubview:_webView];
必须遵守UIWebViewDelegate协议
实现代理方法:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString * requestString = request.URL.absoluteString;
NSLog(@"请求的地址:%@",requestString);
}
requestString 是即将展示的网页的完整路径
H5网页中需要做的:
H5上的按钮需要添加方法,例:<button οnclick="commit()">这是个需要获取的按钮</button>
JS里面实现方法:
function commit(){
window.location.href = "next://";
}
next:// 可以是任意值,只是起到了标识符的作用
这样设置以后,当点击按钮的时候,requestString = "next://";
然后就根据自己的需要,判断requestString的值是什么,要进行什么操作
if ([requestString containsString:@"next://ProductCopyright"]){
//做你想要的操作
HRProductCopyrightViewController * brandRequireVC = [[HRProductCopyrightViewController alloc]init];
[self.navigationController pushViewController:brandRequireVC animated:YES];
}
如果你不想这样做的话,也可以使用JS重写按钮的点击方法,在按钮的点击方法中,直接调用iOS代码,这种方法比较麻烦,就不说了
如果有好的方法,记得给我留言