预读
进入正文
- 第一步:配置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
效果如下:
以上!!!
推荐读: