美文网首页
iOS-OC与Javascript的交互

iOS-OC与Javascript的交互

作者: 良人不归_墨染锦年 | 来源:发表于2018-05-13 21:39 被阅读0次

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

相关文章

网友评论

      本文标题:iOS-OC与Javascript的交互

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