官网教程

如何在 iOS 平台上使用 Javascript 直接调用 Objective-C 方法

报错

1. se报错

需要引入SeApi.h #import "cocos/scripting/js-bindings/jswrapper/SeApi.h"

2. 执行脚本出错

ScriptEngine::evalString script(no filename),failed!ERROR:SyntaxError:Unexpected EOF,location:(no filename):1: STACK: callStaticMethod@[native code]

se::ScriptEngine::getInstance()->evalString(script.c_str()); 在ios这边,script执行的function需要挂在window上面。 js 代码:

window.GlobalFunc = function(paramStr) {

console.log("GlobalFunc ", paramStr)

}

oc 代码:

- (void) postMessageToJs {

se::ScriptEngine::getInstance()->evalString("GlobalFunc(\"hello,js\")");

}

3. 传递json数据

ios 通过 evalString 传递json数据,如果直接json串传递会报错,因为会有双引号问题。为了解决这个问题,可以再加一层编码,比如base64。

- (void) postMessageToJs {

NSMutableDictionary *dict = [NSMutableDictionary dictionary];

[dict setObject:[NSNumber numberWithInt:1001] forKey:@"cmdid"];

[dict setObject@"hello,js" forKey:@"content"];

NSError *error;

NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];

if (data == nil) {

NSLog(@"JSON serialization error: %@", error); // 打印错误信息

return; // 在出现错误时退出方法

}

// 将 JSON 数据进行 Base64 编码

NSString *encodedStr = [data base64EncodedStringWithOptions:0];

NSString *execStr = [NSString stringWithFormat:@"GlobalFunc(\"%@\")",encodedStr];

std::string jsCallStr = [execStr UTF8String];

NSLog(@"postMessageToJs %s", jsCallStr.c_str());

se::ScriptEngine::getInstance()->evalString(jsCallStr.c_str());

}

参考文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: