重新阅读您的描述,您实际上需要了解的是如何使用 WKWebView 重新实现 Javascript/Objective-C 桥。
我自己刚刚按照http://tetontech.wordpress.com/2014/07/17/objective-c-wkwebview-to-javascript-and-back/上的教程和http://上的信息完成了这个nshipster.com/wkwebkit/
WKWebView 具有在 Javascript 和 Objective-C/Swift 之间进行通信的内置方式:WKScriptMessageHandler
.
WKScriptMessageHandler
首先,在视图控制器的标头中包含 WebKit 标头和协议:
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
@interface ViewController : UIViewController <WKScriptMessageHandler>
@end
初始化时WKWebView
,您需要使用脚本消息处理程序对其进行配置。随意命名它,但对我来说,为你的应用程序命名似乎是有意义的。
WKWebViewConfiguration *theConfiguration =
[[WKWebViewConfiguration alloc] init];
[theConfiguration.userContentController
addScriptMessageHandler:self name:@"myApp"];
_theWebView = [[WKWebView alloc] initWithFrame:self.view.frame
configuration:theConfiguration];
[_theWebView loadRequest:request];
[self.view addSubview:_theWebView];
现在,实施userContentController:didReceiveScriptMessage:
. 当您的 webview 收到一条消息时,它会触发,因此它会完成您之前使用webView:shouldStartLoadWithRequest:navigationType:
.
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message {
NSDictionary *sentData = (NSDictionary *)message.body;
NSString *messageString = sentData[@"message"];
NSLog(@"Message received: %@", messageString);
}
您现在已准备好接收来自 Javascript 的消息。您需要添加到 Javascript 的函数调用如下:
window.webkit.messageHandlers.myApp.postMessage({"message":"Hello there"});