zoukankan      html  css  js  c++  java
  • 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];

    }

  • 相关阅读:
    LeetCode Missing Number (简单题)
    LeetCode Valid Anagram (简单题)
    LeetCode Single Number III (xor)
    LeetCode Best Time to Buy and Sell Stock II (简单题)
    LeetCode Move Zeroes (简单题)
    LeetCode Add Digits (规律题)
    DependencyProperty深入浅出
    SQL Server存储机制二
    WPF自定义RoutedEvent事件示例代码
    ViewModel命令ICommand对象定义
  • 原文地址:https://www.cnblogs.com/sunfuyou/p/7658292.html
Copyright © 2011-2022 走看看