美文网首页
ios知识整理:WKWebView,JavaScript向iOS

ios知识整理:WKWebView,JavaScript向iOS

作者: 大布溜 | 来源:发表于2018-03-06 15:17 被阅读84次

    iOS代码.m

    #import <WebKit/WebKit.h>
    @interface XXXXXX ()<WKScriptMessageHandler>
    {
        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:self  name:@"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代码创建样式...可以不管这一部分...关注里面的<script></script>部分就可以了.
         NSString *CSS= @"<style type=\"text/css\">img{margin: 10% 10%;}div{width:100%}h1{font-size:100px;color:#333333;}p{font-size:30px;color:#333333;margin:50px 50px;}</style>";
         NSString * htmlString = [NSString stringWithFormat:@"<html><meta charset=\"UTF-8\"><header>%@<script type=\"text/javascript\">function dismiss(){window.webkit.messageHandlers.ocMethod.postMessage(arguments[0]);}</script></header><body>%@</body></html>",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代码

    <img  onclick="dismiss('5a96bc40fe88c20038ba8e06')" src="article-snack-59f815908d6d810061e9d9d8-1.png"/>
    

    相关文章

      网友评论

          本文标题:ios知识整理:WKWebView,JavaScript向iOS

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