Couldn't call Objective-C method from Cocos-2d via JavaScriptObjCBridge

516 Views Asked by At

URL : https://github.com/cocos-creator/creator-docs/blob/master/en/advanced-topics/oc-reflection.md

Above is the documentation to call a Objective-C method from Cocos script

I trying to do the exact same thing, but I get the error

2020-07-21 15:56:01.094441+0800 hello_world-mobile[63684:4206926] TestingLogging.testingIntegration method isn't found!
[ERROR] (/Applications/CocosCreator/Creator/2.3.3/CocosCreator.app/Contents/Resources/cocos2d-x/cocos/scripting/js-bindings/manual/JavaScriptObjCBridge.mm, 418): call (TestingLogging.testingIntegration) failed, result code: -3
[ERROR] Failed to invoke JavaScriptObjCBridge_callStaticMethod, location: /Applications/CocosCreator/Creator/2.3.3/CocosCreator.app/Contents/Resources/cocos2d-x/cocos/scripting/js-bindings/manual/JavaScriptObjCBridge.mm:427

Screen Shot 2020-07-21 at 4 05 36 PM

.h class

//
//  TestingLogging.h
//  hello_world-mobile
//
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface TestingLogging : NSObject

+(void) testingIntegration: (NSString *) string;

@end

NS_ASSUME_NONNULL_END

.m class

//
//  TestingLogging.m
//  hello_world-mobile
//
//

#import "TestingLogging.h"

@implementation TestingLogging


+(void)testingIntegration:(NSString *)string {
    NSLog(@"First ios call from cocos creator app %@", string);
}

@end

Script in cocos

onCameraClickHandler () {
    if(cc.sys.OS_IOS == cc.sys.os) {           
        var ret = jsb.reflection.callStaticMethod("TestingLogging", "testingIntegration", "Hello iOS")
    }
}

Could you please help me !

1

There are 1 best solutions below

3
Willeke On

In Objective-C the colon is part of the method name. It's mentioned in the linked documentation

methodName parameter in previous example is the OC method name in your class, take NativeOcClass as an example, we can see a method named

+(BOOL)callNativeUIWithTitle:(NSString *)title andContent:(NSString *)content;

So the methodName should be callNativeUIWithTitle:addContent: which is the definition for this method, and don't forget the :.

The name of the method is testingIntegration:. Change the script to

var ret = jsb.reflection.callStaticMethod("TestingLogging", "testingIntegration:", "Hello iOS")