从iOS7开始 苹果公布了JavaScriptCore.framework 它使得JS与OC的交互更加方便了。
下面我们就简单了解一下这个框架
首先我导入framework
方法如下
![](https://img-blog.csdn.net/20150725170931474?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
点击Linked Frameworks and Libraries 的添加后 选择 JavaScriptCore.framework
![](https://img-blog.csdn.net/20150725171216557?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
选中JavaScriptCore.framework后 点击右下角Add 添加完成
好 创建完成之后我们导入一下头文件
- #import <JavaScriptCore/JavaScriptCore.h>
点进去 会看到如下几个方法
#import "JSContext.h"
#import "JSValue.h"
#import "JSManagedValue.h"
#import "JSVirtualMachine.h"
#import "JSExport.h"
这些方法我们等会再细讲
下来我们创建一个UIWebView 用来测试
创建UIWebView
初始化,添加,打开网址
-
- myWebView=[[UIWebView alloc]initWithFrame:CGRectMake(0, 22, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-22)];
- myWebView.delegate=self;
-
- [self.view addSubview:myWebView];
-
-
- NSString *httpStr=@"https://www.baidu.com";
- NSURL *httpUrl=[NSURL URLWithString:httpStr];
- NSURLRequest *httpRequest=[NSURLRequest requestWithURL:httpUrl];
- [myWebView loadRequest:httpRequest];
运行效果如下
![](https://img-blog.csdn.net/20150725174032573?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
下面我们来实现UIWebView的几个代理方法
首先我们看下它的代理方法
- @protocol UIWebViewDelegate <NSObject>
-
- @optional
- - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
- - (void)webViewDidStartLoad:(UIWebView *)webView;
- - (void)webViewDidFinishLoad:(UIWebView *)webView;
- - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;
-
- @end
每个方法的作用等会在带里面做注释
首先我们添加协议
- @interface ViewController ()<UIWebViewDelegate>
实现代理方法
- #pragma mark --webViewDelegate
- -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
- {
-
-
-
- return YES;
- }
-
- -(void)webViewDidStartLoad:(UIWebView *)webView
- {
-
- }
-
- -(void)webViewDidFinishLoad:(UIWebView *)webView
- {
-
- }
-
- -(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
- {
-
- }
每个方法是什么时候调用都在注释里面
下来我们先尝试用oc调用一下js方法
- -(void)webViewDidFinishLoad:(UIWebView *)webView
- {
-
-
-
- JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
- NSString *alertJS=@"alert('test js OC')";
- [context evaluateScript:alertJS];
-
- }
执行效果如下:
![](https://img-blog.csdn.net/20150725181940412?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
好了,我们已经实现了iOS 调用js
js调用iOS 在下节