WKWebView与原生代码交互

原生代码调用js

NSString *evaluateJavaScript = [NSString stringWithFormat:@"h5GetImageUrl(%@)",tempString];
    NSLog(@"js:%@",evaluateJavaScript);
//执行一段JS
    [self.webView evaluateJavaScript:evaluateJavaScript completionHandler:^(id _Nullable object, NSError * _Nullable error) {
        if (error!=nil) {
            [MBProgressHUD showError:@"图片上传失败" toView:self.view];
        }
    }];

js调用原生代码

注册Handler

        let configuration = WKWebViewConfiguration()    // WebView配置
        configuration.userContentController = WKUserContentController()     // 交互对象
        // 添加给js调用的handler   self需要实现WKScriptMessageHandler协议
        configuration.userContentController.add(self, name: "handleName1")
        configuration.userContentController.add(self, name: "handleName2")

WKScriptMessageHandler 协议

public protocol WKScriptMessageHandler : NSObjectProtocol {

    
    /*! @abstract Invoked when a script message is received from a webpage.
     @param userContentController The user content controller invoking the
     delegate method.
     @param message The script message received.
     */
    @available(iOS 8.0, *)
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
}

userContentController: didReceive message: 方法中通过handleName分发业务

public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        if message.name == "" {
            // TODO sth.
        }
    }

js调用代码

//传递空
 window.webkit.messageHandlers.showMobile.postMessage(null)
//传递字符串
window.webkit.messageHandlers.showMobile.postMessage("123") 
//传递数组
window.webkit.messageHandlers.showMobile.postMessage(['1', '2','3'])
//传递字典
window.webkit.messageHandlers.showMobile.postMessage({4: { 'windowID': 10004 } })

你可能感兴趣的:(WKWebView与原生代码交互)