在JavaScript(JS)与Objective-C(OC)的交互中,通常是在iOS应用开发中使用WebView(如WKWebView)时遇到的场景。JS调用OC并获得返回值的过程一般通过以下方式实现:
WKWebViewConfiguration
来配置WebView。WKScriptMessageHandler
来处理从JS发送过来的消息。window.webkit.messageHandlers.<handlerName>.postMessage(<message>)
来调用OC中的方法。<handlerName>
是你在OC中设置的处理器名称。<message>
是传递给OC的消息,可以是字符串、数字或JSON对象。WKScriptMessageHandler
协议的userContentController:didReceiveScriptMessage:
方法来接收JS的消息。OC端:
// ViewController.m
#import "ViewController.h"
#import <WebKit/WebKit.h>
@interface ViewController () <WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView *webView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *userContentController = [[WKUserContentController alloc] init];
[userContentController addScriptMessageHandler:self name:@"nativeHandler"];
configuration.userContentController = userContentController;
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
[self.view addSubview:self.webView];
NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSString *htmlString = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
[self.webView loadHTMLString:htmlString baseURL:[NSBundle mainBundle].resourceURL];
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"nativeHandler"]) {
NSDictionary *body = message.body;
NSString *action = body[@"action"];
if ([action isEqualToString:@"getInfo"]) {
NSDictionary *response = @{@"result": @"Hello from OC!"};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:response options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[self.webView evaluateJavaScript:[NSString stringWithFormat:@"receiveInfoFromOC('%@')", jsonString] completionHandler:nil];
}
}
}
@end
JS端:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>JS调用OC示例</title>
<script>
function callNative() {
window.webkit.messageHandlers.nativeHandler.postMessage({action: "getInfo"});
}
function receiveInfoFromOC(info) {
alert(info.result);
}
</script>
</head>
<body>
<button onclick="callNative()">调用OC方法</button>
</body>
</html>
通过上述方式,JS可以调用OC的方法并接收返回值,实现前后端的无缝对接。
领取专属 10元无门槛券
手把手带您无忧上云