需要用到WebView的协议函数:
测试代码:
- //JS中的button调用OC中的方法
- //WebView每次重定向的时候会调用<UIWebViewDelegate>协议中的方法,
- //无论地址是否合法,协议方法shouldStartLoadWithRequest都会被调用,
- //这样我们就可以在JS中button的触发函数中使网页重定向到我们自定义的地址中,
- //这样OC中的UIWebViewDelegate协议中的shouldStartLoadWithRequest就会被调用,
- -(void)ocFunc
- {
- NSLog(@"我是OC方法");
- }
- //(重定向之后)
- -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
- {
- // //刷新地址栏
- // if ([request.URL.absoluteString hasPrefix:@"http"]) {
- // _textFeild.text = request.URL.absoluteString;
- // }
- _textFeild.text = request.URL.absoluteString;
- // ://
- NSArray *array = [request.URL.absoluteString componentsSeparatedByString:@"://"];
- if ([[array objectAtIndex:0] isEqualToString:@"oc"]) {
- NSString *ocStr = [array objectAtIndex:1];
- //通过字符串调用函数
- SEL sel = NSSelectorFromString(ocStr);
- [self performSelector:sel];
- }
- return YES;
- }