iOS与js互相调用的简单方法实现

#import

#import

1、遵守3个代理   

2、@property (nonatomic, strong) WKWebView *webView;

3、self.view .backgroundColor =[UIColor whiteColor];

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

//注册方法名称,iOS与js保持一致

    [configuration.userContentController addScriptMessageHandler:self name:@"clickFunc"];

    self.webView= [[WKWebViewalloc]initWithFrame:self.view.boundsconfiguration:configuration];

    self.webView.UIDelegate = self;        //记得实现对应协议,不然方法不会实现.

    self.webView.navigationDelegate =self;

    [self.viewaddSubview:self.webView];

    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"h5地址"]]];

4、实现代理方法

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

{

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

    if([message.nameisEqualToString:@"clickFunc"]) {

        [selfclickFunc];

    }

}

5、- (void)clickFunc

{

    NSLog(@"111111");

}

6、js调用window.webkit.messageHandlers.约定的方法名称.postMessage(参数);

你可能感兴趣的:(iOS与js互相调用的简单方法实现)