tsd*_*ter 7 javascript events objective-c cocoaasyncsocket cordova
我希望能够为我的应用程序使用PhoneGap.我将不得不构建一个自定义协议/插件,以便我可以从Javascript调用Native方法.我知道当本机代码返回时,您可以在Javascript中调用成功函数.
我需要做的是从本机代码调用javascript函数.基本上,应用程序将通过本地网络连接到OSX配套应用程序,当OSX应用程序将数据发送到iOS应用程序时,它将以Objective C方式处理,我需要能够将结果发送到PhoneGap/javascript并执行某些操作在WebView中使用它.
这可能吗?我只能从javascript中找到有关调用native的信息,而不是相反.
谢谢,托马斯
使用下面的答案中的代码:
MyPhoneGapPlugin.m
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
NSLog(@"Connected To %@:%i.", host, port);
NSString* jsString = [NSString stringWithFormat:@"alert(connected to: %@);", host];
[theWebView stringByEvaluatingJavaScriptFromString:jsString];
[self readWithTag:2];
}
Run Code Online (Sandbox Code Playgroud)
给我错误'未知接收器'theWebView'你的意思是'UIWebView'?
更新:找到答案:使用phonegap助手我可以写这样的东西......
[super writeJavascript:@"alert('connected');"];
Run Code Online (Sandbox Code Playgroud)
dar*_*s0n 10
您可以使用以下命令从本机代码轻松调用JavaScript UIWebView:
[webView stringByEvaluatingJavaScriptFromString:@"myJSFunction()"];
Run Code Online (Sandbox Code Playgroud)
要将某个函数的结果用作JS函数的arg:
NSString *stringData = getStringData(); // however you get it
[webView stringByEvaluatingJavaScriptFromString:
[NSString stringWithFormat:@"myJSFunction(%@)", stringData]];
Run Code Online (Sandbox Code Playgroud)
找到 PhoneGap 帮助程序来完成此操作...使用以下方法将 javascript 写入 webView:
[super writeJavascript:@"alert('it works');"];
Run Code Online (Sandbox Code Playgroud)