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];

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM