預(yù)讀
進(jìn)入正文
- 第一步:配置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
- 第二步:實(shí)現(xiàn)代理
#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//取出html中的js執(zhí)行環(huán)境 固定寫法
JSContext *jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//實(shí)現(xiàn)html中jsBack函數(shù)(給其傳入一個(gè)block) js->oc
jsContext[@"addProductToCartWithMove"] = ^(NSInteger brandID, NSInteger success, NSInteger error) {
NSLog(@"%zd",brandID);
dispatch_async(dispatch_get_main_queue(), ^{
[self showMsg:[NSString stringWithFormat:@"產(chǎn)品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];
}
補(bǔ)充導(dǎo)入頭文件、兩個(gè)屬性和協(xié)議
#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
以上!??!
嘬奶.gif
推薦讀: