美文网首页
JS与oc交互

JS与oc交互

作者: JasonEVA | 来源:发表于2016-08-16 15:44 被阅读428次

    前言

    之前没有仔细接触过H5的接入,一直以为只需要放url进webView就不用管了。现在有需求需要接入H5页面,发现并没有这么简单,还需要跟JS进行交互,完成一定功能,如获取当前页面的titel,点击跳转后的titel等。这里只是记录下简单的JS交互过程。

    JS和oc进行交互的方式有很多,这里主要是介绍使用JavaScriptCore桥接JS和oc,使JS能够调用oc的原生方法。过程中碰到了内存泄漏的情况,后来使用model注入的方法解决了。

    上代码

    WebViewDemoViewController.h

    #import <UIKit/UIKit.h>
    
    
    @interface WebViewDemoViewController : UIViewController 
    
    @end
    
    

    WebViewDemoViewController.m

    #import "WebViewDemoViewController.h"
    #import <JavaScriptCore/JavaScriptCore.h>
    #import "MedicalFormulaJSModel.h"
    
    @interface WebViewDemoViewController ()<UIWebViewDelegate,MedicalFormulaJSModelDelegate>
    @property (nonatomic, strong) UIWebView *webView;
    @property (nonatomic, weak) JSContext *context;
    
    @end
    
    @implementation WebViewDemoViewController
    -(void)dealloc {
        NSLog(@"销毁了webview");
    }
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        [self.navigationItem setHidesBackButton:YES];
        UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(backClick)];
        [self.navigationItem setLeftBarButtonItem:leftBtn];
    
        self.webView = [[UIWebView alloc] initWithFrame:self.view.frame];
        self.webView.delegate = self;
        NSURL *url = [NSURL URLWithString:@"http://www.test.com"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        self.webView.scalesPageToFit = YES;
        [self.webView loadRequest:request];
        
        [self.view addSubview:self.webView];
        [self.navigationItem setTitle:@"医学公式"];
        // Do any additional setup after loading the view.
    }
    - (void)backClick {
        if (self.webView.canGoBack) {
            [self.webView goBack];
            [self.navigationItem setTitle:@"医学公式"];
        }
        else {
            if (self.navigationController.childViewControllers.count > 1) {
                [self.navigationController popViewControllerAnimated:YES];
            }
            else {
                return;
            }
        }
    }
    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        //通过模型注入,防止内存泄漏
        MedicalFormulaJSModel *model = [MedicalFormulaJSModel new];
        self.context[@"ClientJS"] = model;
        model.jsContext = self.context;
        model.webView = self.webView;
        [model setDelegate:self];
        self.context.exceptionHandler =
        ^(JSContext *context, JSValue *exceptionValue)
        {
            context.exception = exceptionValue;
            NSLog(@"%@", exceptionValue);
        };
    }
    
    - (void)webViewDidStartLoad:(UIWebView *)webView {
        
    }
    
    - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
        
    }
    
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
        return YES;
    }
    
    //实现回调方法,设置titel
    - (void)MedicalFormulaJSModelDelegateCallBack_titel:(NSString *)titel {
        [self.navigationItem setTitle:titel];
    }
    
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    /*
    #pragma mark - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */
    
    @end
    
    

    解释WebViewDemoViewController.m

    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        //通过模型注入,防止内存泄漏
        MedicalFormulaJSModel *model = [MedicalFormulaJSModel new];
        self.context[@"ClientJS"] = model;
        model.jsContext = self.context;
        model.webView = self.webView;
        [model setDelegate:self];
        self.context.exceptionHandler =
        ^(JSContext *context, JSValue *exceptionValue)
        {
            context.exception = exceptionValue;
            NSLog(@"%@", exceptionValue);
        };
    }
    
    

    1.documentView.webView.mainFrame.javaScriptContext这个Path是别的大神那边扒来的,大家通用的获取JSContext的路径
    2.ClientJS是和web前端约定好的JS和oc桥接的桥梁对象,通过将这个桥梁对象注入iOS端的webView,JS前端就可以通过这个桥梁对象去调用原生应用的方法
    3.MedicalFormulaJSModel是为了防止内存泄漏而创建的注入model,因为如果不使用注入model的话直接将JSContext注入VC

    self.context[@"ClientJS"] = self;
    

    这样JSContext环境引用控制器self,在退出控制器的时候,因为控制器self被JSContext引用而不释放,而JSContext只有等控制器释放了才能随之释放,所以就引起了循环引用,造成内存泄露。可以通过dealloc方法查看控制器有没有被释放。

    MedicalFormulaJSModel.h

    //
    //  MedicalFormulaJSModel.h
    //  MintmedicalSDK
    //
    //  Created by jasonwang on 16/8/16.
    //  Copyright © 2016年 JasonWang. All rights reserved.
    //  js注入模型 防止内存泄漏
    
    #import <Foundation/Foundation.h>
    #import <JavaScriptCore/JavaScriptCore.h>
    @class UIWebView;
    @protocol MintMedicalDocToolWebViewSExportProtocol <JSExport> //这是一个协议,如果采用协议的方法交互,自己定义的协议必须遵守此协议
    //方法名需要和web前端协商定好一样,否则调用不到
    - (void)getToolName:(NSString *)title;
    
    @end
    
    @protocol MedicalFormulaJSModelDelegate <NSObject>   //模型的回调方法
    
    - (void)MedicalFormulaJSModelDelegateCallBack_titel:(NSString *)titel;
    
    @end
    
    @interface MedicalFormulaJSModel : NSObject <MintMedicalDocToolWebViewSExportProtocol>
    @property (nonatomic, weak)id<MedicalFormulaJSModelDelegate> delegate;
    @property (nonatomic, weak) JSContext *jsContext;
    @property (nonatomic, weak) UIWebView *webView;
    @end
    
    

    解释MedicalFormulaJSModel.h

    1.MintMedicalDocToolWebViewSExportProtocol交互方法协议这个协议必须要遵守JSExport协议,与JS有交互的方法写在里面

    @protocol MintMedicalDocToolWebViewSExportProtocol <JSExport> //这是一个协议,如果采用协议的方法交互,自己定义的协议必须遵守此协议
    //方法名需要和web前端协商定好一样,否则调用不到
    - (void)getToolName:(NSString *)title;
    
    @end
    

    2.model遵守上面自定义的协议

    @interface MedicalFormulaJSModel : NSObject <MintMedicalDocToolWebViewSExportProtocol>
    

    MedicalFormulaJSModel.m

    #import "MedicalFormulaJSModel.h"
    
    @implementation MedicalFormulaJSModel
    
    - (void)getToolName:(NSString *)title{
        if ([self.delegate respondsToSelector:@selector(MedicalFormulaJSModelDelegateCallBack_titel:)]) {
            [self.delegate MedicalFormulaJSModelDelegateCallBack_titel:title];
        }
    }
    @end
    
    

    参考

    Objective-C与JavaScript交互的那些事

    JavaScript和Objective-C交互的那些事(续)
    iOS与JS交互实战篇(ObjC版)

    相关文章

      网友评论

          本文标题:JS与oc交互

          本文链接:https://www.haomeiwen.com/subject/juypsttx.html