Html中用js回调OC方法

来源:互联网 发布:诸神黄昏灵羽进阶数据 编辑:程序博客网 时间:2024/05/16 00:31

朋友是做安卓的,她在html中成功回调了安卓的方法,问我ios怎么回调。这个东东没做过啊,赶紧问度娘,原来要用到JavaScriptCore.framework.

啥都不说了,先贴代码
ViewController.h

#import <UIKit/UIKit.h>#import <JavaScriptCore/JavaScriptCore.h>@interface ViewController : UIViewController@property (strong, nonatomic) IBOutlet UIWebView *webView;@end

ViewController.m

#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path]]];    JSContext *context = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];    context[@"callOC"] = ^()    {        NSLog(@"+++++++callOC+++++++");    };}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

index.html

<!DOCTYPE html><html>    <head>        <meta charset="utf-8">        <meta name="viewport" content="width=device-width,user-scalable=no" />        <title>HTML中用JS调用OC方法</title>        <script type="text/javascript" language="javascript">            function onClick() {                if (navigator.userAgent.indexOf('AppleWebKit') >= 0)                {                    callOC();                    return;                }                //其他处理            }        </script>    </head>    <body>        <input type="button" value="求求你点我吧" onclick="onClick()" />    </body></html>
0 0
原创粉丝点击