控制器.m的实现如下
#import "ViewController.h"
@interface ViewController () <UIWebViewDelegate>
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// 1.webView
UIWebView *webView = [[UIWebView alloc] init];
webView.frame = self.view.bounds;
webView.delegate = self;
[self.view addSubview:webView];
// 2.加载网页
NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
}
#pragma mark - UIWebViewDelegate
/**
* webView每当发送一个请求之前,都会先调用这个方法(能拦截所有请求),利用这个特性,和服务器协商一个自定义的协议头,如“test://”
js中的响应的方法代码如下
function fn_call() {
window.location.href = 'test://call';
}
*/
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *url = request.URL.absoluteString;
NSRange range = [url rangeOfString:@"test://"];
NSUInteger loc = range.location;
if (loc != NSNotFound) { // url的协议头是test
// 方法名
NSString *method = [url substringFromIndex:loc + range.length];
// 转成SEL
SEL sel = NSSelectorFromString(method);
[self performSelector:sel withObject:nil];
}
return YES;
}
/**
* 打电话
*/
- (void)call
{
NSLog(@"call----");
}
/**
* 打开照相机
*/
- (void)openCamera
{
NSLog(@"openCamera----");
}
@end
说明:个人原创,未经许可不得转载。