JS调用OC方法(webviewDelegate)

oc:

#import "JSOCViewController.h"

@interface JSOCViewController ()<UIWebViewDelegate>

@end

@implementation JSOCViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"JS调用OC";

    UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 40, self.view.frame.size.width, self.view.frame.size.height-40)];
    webView.delegate = self;
    NSString *path = [[NSBundle mainBundle]pathForResource:@"index" ofType:@"html"];
    NSURL *url = [NSURL fileURLWithPath:path];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
    [self.view addSubview:webView];
}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *urlstr = request.URL.absoluteString;
    NSRange range = [urlstr rangeOfString:@"ios://zw"];
    if (range.length!=0) {
        [self show];
    }
    return YES;
}

-(void)show{
    NSLog(@"JS调用OC");
}

html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
 <meta charset="utf-8">
 <title>OC与JS互相调用</title>
</head>
<body>
    <input type="button" value="JS调用OC方法" onclick="js_call_oc()"/>
    <script type="text/javascript">
        function js_call_oc()
        {
                var iFrame;
                iFrame = document.createElement("iframe");
                iFrame.setAttribute("src", "ios://zw");
                iFrame.setAttribute("style", "display:none;");
                iFrame.setAttribute("height", "0px");
                iFrame.setAttribute("width", "0px");
                iFrame.setAttribute("frameborder", "0");
                document.body.appendChild(iFrame);
                // 发起请求后这个iFrame就没用了,把它从dom上移除掉
                iFrame.parentNode.removeChild(iFrame);
                iFrame = null;
          }
    </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值