iOS开发之JS与OC交互(UIWebView篇)

预读

iOS开发之JS与OC交互(WKWebView篇)

进入正文

  • 第一步:配置UIWebView:
- (void)configWebView{
    UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    NSURL *url = [NSURL URLWithString:@"https://m.benlai.com/huanan/zt/1231cherry"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
    [self.view addSubview:webView];
    self.webView = webView;
    
    webView.delegate = self;
}
//宏定义:
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
  • 第二步:实现代理
#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    //取出html中的js执行环境  固定写法
    JSContext *jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    //实现html中jsBack函数(给其传入一个block)  js->oc
    jsContext[@"addProductToCartWithMove"] = ^(NSInteger brandID, NSInteger success, NSInteger error) {
        NSLog(@"%zd",brandID);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showMsg:[NSString stringWithFormat:@"产品ID:%zd",brandID]];
        });
    };
    self.webJSContext = jsContext;
}

附带私有方法showMsg:

#pragma mark - private
- (void)showMsg:(NSString *)msg {
    [[[UIAlertView alloc] initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil] show];
}

补充导入头文件、两个属性和协议

#import 
#import 
@interface KODWebViewController () 

@property(nonatomic, weak) UIWebView *webView;
@property(nonatomic, strong) JSContext *webJSContext;

@end

效果如下:

iOS开发之JS与OC交互(UIWebView篇)_第1张图片
Snip20180115_18.png

DEMO传送门

以上!!!


iOS开发之JS与OC交互(UIWebView篇)_第2张图片
嘬奶.gif

推荐读:

iOS开发之UIWebView和WKWebView使用上的差别

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