繁体   English   中英

将obj-c类传递给javascript不起作用。 我究竟做错了什么?

[英]Passing obj-c class to javascript doesn't work. What am I doing wrong?

我正在用javascript编写一些后端代码,并计划将本机代码用于GUI。 在Android上,这完全可以正常工作,但是在Mac OS X上的Cocoa中,使它无法正常工作时,我遇到了一些问题。我已经按照Apple的教程进行了操作,但这是行不通的。 看完代码后,让我尝试解释一下。

的index.html

<html>
<head>
    <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", ready, false);

        function ready() {
            document.write(returnString());
            bridge.onBackendReady();
        }

        function returnString() {
            return "Hello World!!!!";
        }
    </script>
</head>
<body>

</body>
</html>

AppDelegate.m

#import "AppDelegate.h"
#import "BackendBridge.h"


@implementation AppDelegate

@synthesize webview;
@synthesize backend;


-(void)applicationDidFinishLaunching:(NSNotification *)notification
{
backend = [[BackendBridge alloc] init];

NSString *backendPath = [[NSBundle mainBundle] pathForResource:@"Index" ofType:@"html"];
NSURL *backendUrl = [NSURL fileURLWithPath:backendPath];

[[webview mainFrame] loadRequest:[NSURLRequest requestWithURL:backendUrl]];
[[webview windowScriptObject] setValue:backend forKey:@"bridge"];
}

@end

BackendBridge.m

#import "BackendBridge.h"


@implementation BackendBridge

-(void)onBackendReady
{
NSLog(@"Ready");
}

@end

所以,我在这里要做的很简单。 从javascript调用BackendBridge类中的onBackendReady函数。 从我从Apple WebView api和教程中了解的内容来看,这应该是正确的方法,但是它不起作用(NSLog调用不会运行)。 我知道javascript函数可以按预期工作,因为在我的ui中,我可以看到字符串“ Hello World !!!!” ...

WebScriptObject.h的注释说:

By default, no properties or functions are exported. A class must implement
+isKeyExcludedFromWebScript: and/or +isSelectorExcludedFromWebScript: to 
expose selected properties and methods, respectively, to JavaScript.

也许将其添加到BackendBridge

+ (BOOL)isSelectorExcludedFromWebScript:(SEL)selector
{
    return selector != @selector(onBackendReady);
}

bridge_onBackendReady();

使用下划线代替。 要么 :

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM