标签:
用途:在ios开发中,经常回用到js调用oc代码的时候,例如在网页上有个拍照和打电话的按钮,想打开系统自带的拍照和电话的时候,就需要用到js调用oc代码的功能。
实现原理:在webView加载html网页的时候,没当发送一个请求,就会调用<UIWebViewDelegate>代理的
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType方法从而实现对oc代码的调用
oc代码如下:
#import "HMViewController.h" @interface HMViewController () <UIWebViewDelegate> @end @implementation HMViewController - (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 - (void)webViewDidFinishLoad:(UIWebView *)webView { } /** * webView每当发送一个请求之前,都会先调用这个方法(能拦截所有请求) */ - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *url = request.URL.absoluteString; NSRange range = [url rangeOfString:@"hm://"]; NSUInteger loc = range.location; if (loc != NSNotFound) { // url的协议头是hm // 方法名 NSString *method = [url substringFromIndex:loc + range.length]; // 转成SEL SEL sel = NSSelectorFromString(method);//把url前面没用的去掉。只留剩下的方法名。 [self performSelector:sel withObject:nil]; } return YES; } /** * 打电话 */ - (void)call { NSLog(@"call----"); } /** * 打开照相机 */ - (void)openCamera { NSLog(@"openCamera----"); } @end
test.html的代码如下:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <p></p> <div> <button onclick="fn_open_camera();">拍照</button> </div> <p></p> <div> <button onclick="fn_call();">打电话</button> </div> <a href="http://www.baidu.com">百度</a> <script> function fn_call() { // 调用OC中call方法 window.location.href = ‘hm://call‘;//hm可以随便写,但是要和oc中截取的协议头一致 } function fn_open_camera() { // 调用OC中openCamera方法 window.location.href = ‘hm://openCamera‘; } </script> </body> </html>
标签:
原文地址:http://www.cnblogs.com/meiyou5866/p/4669498.html