iOS开发中OC与JS的交互

import "ViewController.h"

import

@interface ViewController ()
@property(nonatomic,strong) JSContext *jsContext;
@property(nonatomic,strong)UIWebView *web;
@end

@implementation ViewController

-(void)viewDidLoad {

[super viewDidLoad];
//设置代理

self.web.delegate = self;

[self checkWebCart];

}

-(void)loadWebView:(NSString *)strUrl
{

if (strUrl) {

NSURL *weburl = [NSURL URLWithString:@"url"];

NSURLRequest *request =[NSURLRequest requestWithURL:weburl];

[self.web loadRequest:request];

}

}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{

//创建JSContext 对象(此处通过当前webView的键获取到jscontext)

self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];


//js调用iOS
//js的方法名称,赋给是一个block 里面是iOS代码,方法名(networkSetFinished)h5人员提供
//没参数就为空,可以获取到JS传过来的值
self.jsContext[@"networkSetFinished"] = ^(int state,NSString * msg) {
    
    // 主线程执行:
    dispatch_async(dispatch_get_main_queue(), ^{
        
    });
    
};

//点击web页面按钮的响应
self.jsContext[@"NotifyCart"] = ^(NSString * state) {
    
    NSLog(@"main:%d",[state intValue]);
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NotifyCart" 

object:[NSString stringWithFormat:@"%d", [state intValue]]];

};

}

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

(UIWebViewNavigationType)navigationType{

//判断是否单击,页面的点击进行拦截,返回NO即拦截
if (navigationType == UIWebViewNavigationTypeLinkClicked){
//判断点击响应的URL路径是否包含该方法名
    if ([[request.URL path] containsString:@"/ChouJiang/"]){
    //进行局部点击跳转
        return NO;
    }
    
    
    //在这里可以获取对应的URL 进行页面跳转加载   request.URL 如
    UIViewController *vc = [[UIViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    return NO;
    
}

return YES;

}

//传值给web

-(void)checkWebCart
{

NSString * checkWebCart =[NSString stringWithFormat:@"appJumpToCar()"]; //准备执行的js代码

self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
    context.exception = exceptionValue;
    NSLog(@"异常信息:%@", exceptionValue);
};
//传值一般利用到了 stringByEvaluatingJavaScriptFromString
[self.web stringByEvaluatingJavaScriptFromString:checkWebCart];

}

@end

你可能感兴趣的:(iOS开发中OC与JS的交互)