美文网首页js交互
iOS开发之JS与OC交互(UIWebView篇)

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

作者: KODIE | 来源:发表于2018-01-15 16:07 被阅读0次

预读

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 <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
@interface KODWebViewController () <UIWebViewDelegate>

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

@end

效果如下:

Snip20180115_18.png

DEMO传送门

以上!!!


嘬奶.gif

推荐读:

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

相关文章

网友评论

    本文标题:iOS开发之JS与OC交互(UIWebView篇)

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