JS调用OC简单实例-part1

<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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值