• oc调javascript方法(evaluateJavaScript:)&&js给oc发通知


    在ios8中引入了WKWebView控件,通过在头文件引用

    #import <WebKit/WebKit.h>来使用该控件,

    这个控件与oc的原生控件uiwebview很相似,它更方便oc与js的相互通讯。

    1.oc调用js方法例子:

    通过方法:

    - (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id,NSError*))completionHandler;

    调用js中的方法,例如我们可以这样使用这个方法:

    - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{

       NSString *promptCode = [NSStringstringWithFormat:@"mymethd("%@")",self.data];

         [_theWebView evaluateJavaScript:promptCode completionHandler:^(id object,NSError *error) { }];

    }

    当wkwebview把html加载完之后,调用此方法,其中@"mymethd("%@")",是方法名和要传的参数

    2.js给oc发送通知例子:

    - (void)viewDidLoad {

        NSString *path = [[NSBundlemainBundle]pathForResource:@"htmlname"ofType:@"html"];

       NSURL *url = [NSURLfileURLWithPath:path];

       NSURLRequest *request = [NSURLRequestrequestWithURL:url];

       WKWebViewConfiguration *theConfiguration =

        [[WKWebViewConfigurationalloc]init];

        [theConfiguration.userContentController

         addScriptMessageHandler:selfname:@"myName"];

        _theWebView = [[WKWebViewalloc]initWithFrame:self.view.frame

                                        configuration:theConfiguration];   

        _theWebView.navigationDelegate =self; 

    //- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation方法代理

        [_theWebViewloadRequest:request];

        [self.viewaddSubview:_theWebView];

    }

     
    在js方法中这样给oc发送通知:

    function postMyMessageA()

            {

               var message = {'message' :'You choose the A'};

                window.webkit.messageHandlers.myName.postMessage(message);

            }

     

    这是oc中收到通知后回调的方法:

    - (void)userContentController:(WKUserContentController *)userContentController

          didReceiveScriptMessage:(WKScriptMessage *)message

    {

       NSDictionary * messageDic = [[NSDictionaryalloc]initWithDictionary:message.body];

       NSString * messageStr = [messageDicobjectForKey:@"message"];

        UIAlertView * messAlert = [[UIAlertViewalloc]initWithTitle:nilmessage:messageStrdelegate:nilcancelButtonTitle:@"yes"otherButtonTitles:nil,nil];

        [messAlertshow];

    }

  • 相关阅读:
    面向对象编程(二)封装--构造方法,this关键字,static关键字,方法重载
    面向对象编程(四)继承,概念及super关键字,final关键字,Object类常见方法
    Python学习4--字符串
    python学习3--元祖
    数据挖掘概念与技术14--Star-Cubing
    Python学习2--列表
    数据挖掘概念与技术13--BUC
    数据挖掘概念与技术12--数据立方体的计算和多路数组聚集详解
    Python学习1--数据类型与循环要点
    数据挖掘概念与技术11--数据仓库的实现
  • 原文地址:https://www.cnblogs.com/sunfuyou/p/7658292.html
Copyright © 2020-2023  润新知