ios知识整理:WKWebView|ios知识整理:WKWebView,JavaScript向iOS传参

【ios知识整理:WKWebView|ios知识整理:WKWebView,JavaScript向iOS传参】iOS代码.m
#import @interface XXXXXX () { WKWebView *_webview; LikeRoDislikeView *_likeOrDislikeView; } @property (strong, nonatomic) WKUserContentController *userContent; @end@implementation XXXXXX -(instancetype)init { self = [super init]; if (self) { WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; self.userContent = [[WKUserContentController alloc] init]; [self.userContent addScriptMessageHandler:selfname:@"ocMethod"]; config.userContentController = self.userContent; _webview = [[WKWebView alloc] initWithFrame:self.view.frame configuration:config]; ; _webview.frame = self.view.frame; _webview.scrollView.delegate = self; [self.view addSubview:_webview]; } return self; }- (void)这个方法是我从自己的后台获取html的代码:(NSString *)urlString{ //给自己的从后台获取的html代码创建样式...可以不管这一部分...关注里面的部分就可以了. NSString *CSS= @"img{margin: 10% 10%; }div{width:100%}h1{font-size:100px; color:#333333; }p{font-size:30px; color:#333333; margin:50px 50px; }"; NSString * htmlString = [NSString stringWithFormat:@"%@%@",CSS,urlString]; //这个基础url是我本地缓存图片的位置.. 可以不管这个... // 获取当前应用的根目录 NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp"]; NSURL *baseURL = [NSURL fileURLWithPath:path]; //body是服务器返回的html格式的文章代码 [_webview loadHTMLString:htmlString baseURL:baseURL]; }-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { NSString *messageName = message.name; if ([@"ocMethod" isEqualToString:messageName]) { id messageBody = message.body; NSLog(@"%@",messageBody); } } @end

html代码
ios知识整理:WKWebView|ios知识整理:WKWebView,JavaScript向iOS传参
文章图片

    推荐阅读