<pre name="code" class="objc">原理通过viewcontroller当中的来检测response.url,然后将该字符串分解,抽取出方法,再通过performSelector调用oc方法
</pre><pre code_snippet_id="1652847" snippet_file_name="blog_20160419_1_2828693" name="code" class="html"></pre><pre code_snippet_id="1652847" snippet_file_name="blog_20160419_1_2828693" name="code" class="html">
<html>
<meta charset='UTF-8'/>
<title>js调用oc的打电话的方法</title>
<script>
function call(){
location.href='hq://call';
}
</script>
<body>
<button οnclick='call()'>打电话给10086</button>
</body>
</html>
//
// ViewController.m
// JSCallsOC
//
// Created by hq on 16/4/19.
// Copyright © 2016年 hanqing. All rights reserved.
//
#import "ViewController.h"
@interface ViewController () <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url=[[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
[self.webView loadRequest:[NSURLRequest requestWithURL:url]];
self.webView.delegate=self;
}
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//js调用oc原理,通过特殊的url解析方法,然后调用oc的相应方法
NSString *urlString=request.URL.absoluteString;
//我们制定了一个协议,调用oc的方法都以hq://开头,后边跟着方法名
NSString *scheme=@"hq://";
//如果是我们自定义的协议hq://call
if ([urlString containsString:scheme]) {
NSString *methodName=[urlString substringFromIndex:scheme.length];
[self performSelector:NSSelectorFromString(methodName) withObject:nil];
return NO;
}
NSLog(@"%@",request.URL);
return YES;
}
-(void) call{
NSLog(@"打电话给10086");
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://10086"]];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end