Js与Oc交互总结

1.Oc调用Js方法

 (1)JS调用OC-URL方法

     

示例1、准备一个本地化的html网页,如jsIOS.html

<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=utf-8">
        <title>js调用oc</title>
        <script type="text/javaScript">
            function postStr(){
                 return document.getElementById("text1").value;
                 //return "javaScript返回值啦";
            }
        </script>
    </head>
    <body>
      <p><input type="text" id="text1" value="返回值"/></p>
      <p><input type="button" id="btn" value="提交" onclick="postStr()"/></p>
    </body>
</html>

2、将此html文件放到项目代码目录里面,如图:

 

3、拖一个UIWebView控件和UIButton控件到xxxViewController对应的.xib或.storyboard视图的UIView上;

在xxxViewController的.h文件中分别声明UIWebView类型变量和UIButton类型的变量,以及一个按钮点击事件(并且跟视图里面的控件连线),

并且添加一个UIWebViewDelegate类型的委托。

xxxViewController.h文件内容如下:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIWebViewDelegate>
@property(nonatomic,retain) IBOutlet UIWebView *webview;
@property(nonatomic,retain) IBOutlet UIButton *button;
-(IBAction)IOS_JS:(id)sender;
@end
4、在xxxViewController.m文件中实现通过点击事件,调用javaScript的方法并取得返回值。 

代码如下:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize webview;

- (void)viewDidLoad
{
    [super viewDidLoad];
    //设置webView
	webview.backgroundColor = [UIColor clearColor];
    //webview.scalesPageToFit =YES;
    webview.delegate =self;
    //找到jsIOS.html文件的路径
    NSString *basePath = [[NSBundle mainBundle]bundlePath];
    NSString *helpHtmlPath = [basePath stringByAppendingPathComponent:@"jsIOS.html"];
    NSURL *url = [NSURL fileURLWithPath:helpHtmlPath];
    //加载本地html文件
    [webview loadRequest:[NSURLRequest requestWithURL:url]];
}

/*
 * 点击事件
 * 调用javaScript的方法postStr()并取得返回值
 * 输出返回值到控制台
 */
-(IBAction)IOS_JS:(id)sender
{
    NSString *str = [self.webview stringByEvaluatingJavaScriptFromString:@"postStr();"];
    NSLog(@"JS返回值:%@",str);
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
@end
 
 
(2)JS调用OC第二方法(JavaScriptCore)

首先我导入

#import <JavaScriptCore/JavaScriptCore.h>

方法如下

点击Linked Frameworks and Libraries 的添加后 选择 JavaScriptCore.framework

选中JavaScriptCore.framework后 点击右下角Add 添加完成

好 创建完成之后我们导入一下头文件

[objc]  view plain  copy
  1. #import <JavaScriptCore/JavaScriptCore.h>  

点进去 会看到如下几个方法

#import "JSContext.h"

#import "JSValue.h"

#import "JSManagedValue.h"

#import "JSVirtualMachine.h"

#import "JSExport.h"


这些方法我们等会再细讲

下来我们创建一个UIWebView  用来测试

创建UIWebView

[objc]  view plain  copy
  1. UIWebView *myWebView;  

初始化,添加,打开网址

[objc]  view plain  copy
  1. //初始化webview  
  2. myWebView=[[UIWebView alloc]initWithFrame:CGRectMake(022, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-22)];  
  3. myWebView.delegate=self;  
  4. //添加webview到当前viewcontroller的view上  
  5. [self.view addSubview:myWebView];  
  6.   
  7. //网址  
  8. NSString *httpStr=@"https://www.baidu.com";  
  9. NSURL *httpUrl=[NSURL URLWithString:httpStr];  
  10. NSURLRequest *httpRequest=[NSURLRequest requestWithURL:httpUrl];  
  11. [myWebView loadRequest:httpRequest];  


运行效果如下

下面我们来实现UIWebView的几个代理方法

首先我们看下它的代理方法

[objc]  view plain  copy
  1. @protocol UIWebViewDelegate <NSObject>  
  2.   
  3. @optional  
  4. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;  
  5. - (void)webViewDidStartLoad:(UIWebView *)webView;  
  6. - (void)webViewDidFinishLoad:(UIWebView *)webView;  
  7. - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;  
  8.   
  9. @end  

每个方法的作用等会在带里面做注释

首先我们添加协议

[objc]  view plain  copy
  1. @interface ViewController ()<UIWebViewDelegate>  

实现代理方法

[objc]  view plain  copy
  1. #pragma mark --webViewDelegate  
  2. -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType  
  3. {  
  4.     //网页加载之前会调用此方法  
  5.       
  6.     //retrun YES 表示正常加载网页 返回NO 将停止网页加载  
  7.     return YES;  
  8. }  
  9.   
  10. -(void)webViewDidStartLoad:(UIWebView *)webView  
  11. {  
  12.     //开始加载网页调用此方法  
  13. }  
  14.   
  15. -(void)webViewDidFinishLoad:(UIWebView *)webView  
  16. {  
  17.     //网页加载完成调用此方法  
  18. }  
  19.   
  20. -(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error  
  21. {  
  22.     //网页加载失败 调用此方法  
  23. }  


每个方法是什么时候调用都在注释里面

下来我们先尝试用oc调用一下js方法

[objc]  view plain  copy
  1. -(void)webViewDidFinishLoad:(UIWebView *)webView  
  2. {  
  3.     //网页加载完成调用此方法  
  4.       
  5.     //首先创建JSContext 对象(此处通过当前webView的键获取到jscontext)  
  6.     JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];  
  7.     NSString *alertJS=@"alert('test js OC')"//准备执行的js代码  
  8.     [context evaluateScript:alertJS];//通过oc方法调用js的alert  
  9.       
  10. }  

执行效果如下:

Js调用Oc方法

(1)JS调用OC-URL方法"

- (void)viewDidLoad {

    [super viewDidLoad];

    self.title =@"URL方法";

    [self loadWeb];

   

}

- (void)loadWeb

{

    NSString *path = [[NSBundle mainBundle] pathForResource:@"JStoOCfirstIndex.html" ofType:nil];

    NSString *htmlString = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

    [self.webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];

   

}

#pragma mark - webViewdelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

{

    NSString *getURLString = [request.URL absoluteString];

    NSLog(@"总的字符串:%@",getURLString);

    

    NSString *htmlHeadString = @"zimu://";

    //协议头可以自己定义可以自己定义

    if([getURLString hasPrefix:htmlHeadString])

    {

        NSString *subString = [getURLString substringFromIndex:htmlHeadString.length];

        NSArray *arrayStr = [subString componentsSeparatedByString:@"?"];

        NSString *fistStr = [arrayStr firstObject];

        NSString *methodName = [fistStr stringByReplacingOccurrencesOfString:@"_" withString:@":"];

        SEL  selector = NSSelectorFromString(methodName);

#pragma clang diagnostic push

#pragma clang diagnostic ignored "-Warc-performSelector-leaks"

        //-Warc-performSelector-leaks为唯一的警告标识

       [self performSelector:selector withObject:[arrayStr lastObject]];

#pragma clang diagnostic pop

        

        //注意:系统提供的方法最多只有两个参数,如果要多个参数,使用我的扩展类

       // - (id)performSelector:(SEL)aSelector withObjects:(NSArray *)objects

        

        return NO;

    }

    else

       return YES;

}

- (void)callName:(NSString *)string

{

    NSLog(@"详细讲解网站是:\n%@",string);

    [LZBAlterView lzb_alterViewWithText:[NSString stringWithFormat:@"传过来的参数:%@",string] OneTitle:@"知道了" TwoTitle:nil ThreeTitle:nil handleBlock:^(LZBAlterView *alterView, NSInteger btntag) {

        [alterView removeAlterView];

    }];

}

(2) OC 调用 JS 第二方法 (JavaScriptCore)

- (void)viewDidLoad {

    [super viewDidLoad];

    self.title = @"OC调用JS方法";

    [self loadWebData];

    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc]initWithCustomView:self.btn]];

   

}

- (void)loadWebData

{

    NSString *path = [[NSBundle mainBundle] pathForResource:@"OCtoJStwoIndex.html" ofType:nil];

    NSURL *localURL = [[NSURL alloc]initFileURLWithPath:path];

    [self.webView loadRequest:[NSURLRequest requestWithURL:localURL]];

}

- (void)handdleOCCallJS

{

    //获得WebView的运行环境的对象

    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

    //调用方法(注意:这里是JS里面的定义的方法)

    NSString *callJSstring = @"sendJSString('参数:OC call JS test 子木')";

    [context evaluateScript:callJSstring];

}

- (UIButton *)btn

{

    if(_btn == nil)

    {

        _btn = [UIButton buttonWithType:UIButtonTypeCustom];

        _btn.backgroundColor = [UIColor redColor];

        _btn.frame = CGRectMake(self.view.center.x - button_Width * 0.5, self.view.center.y, button_Width, button_Height);

        [_btn setTitle:@"点击调用JS" forState:UIControlStateNormal];

        [_btn addTarget:self action:@selector(handdleOCCallJS) forControlEvents:UIControlEventTouchUpInside];

    }

    return _btn;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值