WKWebView的交互

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Lucky_Deng/article/details/53483259

一 现在WKWebView是官方推荐的,在iOS8.0以上的版本都能使用,而且加载速度提高到了很多,虽说它不兼容iOS7.0-iOS8.0,但是还是有非常多的iOS开发者,直接忽略这部分用户,原因就是提升用户体验,我接触的很多人就是直接用WKWebView,

特别重要:UIWebView和WKWebView这两个交互无论前端还是后端他们的交互方法都不一样,都需要写2套,这里说WKWebview就着重说wk吧 后端必须这么写,你才能看到交互的方法被执行。jsParamFunc2:这是约定的方法名 您的订货量超出库存:这个是传的参数,这里传的是字符串,如果多个参数,可以传字典

  window.webkit.messageHandlers.jsParamFunc2.postMessage("您的订货量超出库存");

话不多说,直接上代码首先导入

#import <WebKit/WebKit.h>

再遵循遵循三个代理 ,最后一个是交互的代理,必须使用否则无法实现

WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler


定义一个属性 ,用懒加载

-(WKWebView*)myWebView{

    

    if (!_myWebView) {

        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];

        

        WKUserContentController* userContent = [[WKUserContentController alloc] init];

        

        [userContent addScriptMessageHandler:self name:@"jsParamFunc2"];

       config.userContentController = userContent;

        

        self.myWebView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:config];

        

        self.myWebView.backgroundColor = [UIColor whiteColor];

        self.myWebView.UIDelegate = self;

        self.myWebView.navigationDelegate = self;

        

    }

    return _myWebView;

}

再加载一个html网页:

WKUserContentController *userContentController = [[WKUserContentController alloc] init];

    [userContentController addScriptMessageHandler:self name:@"jsParamFunc2"];

    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];

    configuration.userContentController = userContentController;

    

    [self.myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@" "]]];

    [self.view addSubview:self.myWebView];


然后加载出来点击,下面这个就是交互的方法

-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{

    if ([@"jsParamFunc2" isEqualToString:message.name]) {

        NSLog(@"message.body %@",message.body);

        // 判断message的内容,然后做相应的操作

        

    }

}


message.body  这个就是你交互的后端传给你的值很明显我接收到的是 您的订货量超出库存 没写过几次写的不好敬请谅解


猜你喜欢

转载自blog.csdn.net/Lucky_Deng/article/details/53483259