IOS 与 JS 交互

导入    JavaScriptCore.framework    






准备一个HTML文件:



协议必须继承与 JSExport

#import <Foundation/Foundation.h>

#import <JavaScriptCore/JavaScriptCore.h>


@protocol customJavaScriptDelegate <JSExport>



- (void)call:(NSString * )string;


@end





#import "ViewController.h"

#import "customJavaScriptDelegate.h"


@interface ViewController ()<UIWebViewDelegate,customJavaScriptDelegate>



@property (nonatomic,strong)UIWebView * Web;

@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    self.view.backgroundColor = [UIColororangeColor];

    //获取本地HTML

    NSString * htmlPath = [[NSBundlemainBundle]pathForResource:@"test"ofType:@"html"];

    

    NSURL *url=[NSURLfileURLWithPath:htmlPath];


    //创建一个UIWebView

    self.Web = [[UIWebViewalloc]initWithFrame:CGRectMake(0,150, 400, 300)];

    [self.WebloadRequest:[NSURLRequestrequestWithURL:url]];

    self.Web.delegate =self;

    [self.viewaddSubview:self.Web];

    

    UIButton * button = [[UIButtonalloc ]initWithFrame:CGRectMake(50,550,70,45)];

    [button addTarget:selfaction:@selector(buttonTest:)forControlEvents:UIControlEventTouchUpInside];

    [button setTitle:@"OCJS·"forState:UIControlStateNormal];

    button.backgroundColor = [UIColorredColor];

    [self.viewaddSubview:button];


}


- (void)buttonTest:(UIButton *)sender{

    //调用JS方法并返回值

    NSString * backStr= [self.WebstringByEvaluatingJavaScriptFromString:[NSStringstringWithFormat:@"test4('%@','%@')",@"ABCD",@"EFG"]];

    

    NSLog(@"=============== %@",backStr);

}


//刚要开始加载时调用

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

{

    

    

    NSURL *url=request.URL;

    //判断scheme是否是自定义的

    if([url.schemeisEqualToString:@"native"])

    {

        //判断host是什么方法

        if([url.hostisEqualToString:@"log"])

        {

            //query param拼接起来

            NSString *query=url.query;

            

            //分割字符

            NSArray *arr=[query componentsSeparatedByString:@"&"];

            NSMutableDictionary *dic=[NSMutableDictionarydictionary];

            for(NSString *strin arr)

            {

                NSArray *arrItem=[str componentsSeparatedByString:@"="];

                dic[arrItem[0]]=arrItem[1];

            }

            NSLog(@"输出%@",dic[@"pwd"]);

        }

        return NO;

    }

    return YES;

}


//加载完成后调用

- (void)webViewDidFinishLoad:(UIWebView *)webView

{

    //获取JSContext对象,对应javascript上下文里的window对象

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

    

    //将本类对象注入JS JS调用call方法

    context[@"callOC"] = self;

    

    context[@"log"]=^(NSString * str)

    {

        NSLog(@"===== %@",str);

    };


}


//加载失败后条用

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{

    NSLog(@"error:%@",error);

}


/**

 *  协议方法

 */

- (void)call:(NSString *)param

{

    NSLog(@"JS返回的参数param:%@",param);

    

}



- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end



效果图






控制台:





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值