h5和iOS原生交互,h5和iOS互相传值

前言 : h5和iOS原生交互,互相传值,下面代码是完整的.M文件  简单实现h5和原生交互,互相传值。

//
//  ViewController.m
//  原生-H5简单交互
//
//  Created by Mr Yang on 2018/7/23.
//  Copyright © 2018年 MrYang. All rights reserved.
//
#define ScreemW   [UIScreen mainScreen].bounds.size.width
#define ScreemH   [UIScreen mainScreen].bounds.size.height
#import "ViewController.h"

//引用系统JS库名
#import <JavaScriptCore/JavaScriptCore.h>
//原生创建JS代理方法 用于H5调此方法向原生传值
@protocol JSDelegate <JSExport>
- (void)getImage:(id)parameter;
@end


@interface ViewController ()<UIWebViewDelegate,JSDelegate>

@property(retain, nonatomic) UIWebView *myWebView;
@property(strong, nonatomic) JSContext *jsContext;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupWebView];
}
- (void)setupWebView{
    if (!self.myWebView) {
        //初始化 WebView
        self.myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, ScreemW, ScreemH)];
        self.myWebView.backgroundColor = [UIColor whiteColor];
        self.myWebView.delegate = self;
        NSURL *path = path = [NSURL URLWithString:@"www.baidu.com"];
        [self.myWebView loadRequest:[NSURLRequest requestWithURL:path]];
        [self.view addSubview:self.myWebView];
    }
}
#pragma mark UIWebViewDelegate
// 加载完成开始监听js的方法
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    
    self.jsContext = [self.myWebView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.jsContext[@"iosDelegate"] = self;

    self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exception){
        context.exception = exception;
        NSLog(@"获取 self.jsContext 异常信息:%@",exception);
    };
}

#pragma mark - JSDelegate
- (void)getImage:(id)parameter{
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        // parameter 就是H5给你传的值
        
        JSValue *jsValue = self.jsContext[@"setImageWithPath"];
        
        //调取H5 JS 方法向H5传值
        
        [jsValue callWithArguments:@[@{@"can1":@"",@"can2":@""}]];
    });
    
}


@end

展开阅读全文

没有更多推荐了,返回首页