环境:MAC,xCode11,CocosCreator2.3.1
有关CocosCreator与Object-C如何交互的问题,参考文章:
https://blog.csdn.net/ZFSR05255134/article/details/105587509
cocos creator 文档介绍
https://docs.cocos.com/creator/manual/zh/advanced-topics/oc-reflection.html
在xcode 编辑器中 AppController 类 中定义与实现 initCsjAdSDK 函数。
//初始化Csj SDK
-(void)initCsjAdSDK{
NSLog(@"-------------------1 初始化Csj SDK");
[BUAdSDKManager setAppID:@"应用id"];
[BUAdSDKManager setIsPaidApp:NO];
[BUAdSDKManager setLoglevel:BUAdSDKLogLevelDebug];
// NSLog(<#NSString * _Nonnull format, ...#>);
// 初始化激励视屏
UIViewController *_csjAdReward= [[CsjAdReward alloc] init];
[_viewController.view addSubview:_csjAdReward.view];
}
调用SDK初始化
在 AppController 类 的 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 函数中调用 initCsjAdSDK 函数。
// 初始化Csj SDK
[self initCsjAdSDK];
代码如下:
@interface CsjAdReward : UIViewController{
// int countNum;
}
+(CsjAdReward *) getAdInstance; //用来获取实例的方法
-(void) OpenAd;
-(void) testCallJs;
@end
代码如下:
#import
#import "CsjAdReward.h"
#import
#import
//#import
//#import "AppController.h"
#import
//
#import "CallJS.h"
//#import "RootViewController.h"
@interface CsjAdReward ()
@property (nonatomic,strong) BUNativeExpressRewardedVideoAd *rewardedVideoAd;
@end
static CsjAdReward *instance; //这里声明一下静态实例,方便javascript层调用
@implementation CsjAdReward
//获取实例的方法,方便javascript层调用
+(CsjAdReward *) getAdInstance{
return instance;
}
//初始化,根着SDK文档照做就好了
- (void) viewDidLoad {
NSLog(@"----------viewDidLoad");
instance=self;
// [BUAdSDKManager setAppID:@"应用ID"];
// [BUAdSDKManager setIsPaidApp:NO];
// [BUAdSDKManager setLoglevel:BUAdSDKLogLevelDebug];
BURewardedVideoModel *model=[[BURewardedVideoModel alloc]init];
model.userId=@"ming123";
self.rewardedVideoAd=[[BUNativeExpressRewardedVideoAd alloc] initWithSlotID:@"激励视频ID" rewardedVideoModel:model];
self.rewardedVideoAd.delegate=self;
[self.rewardedVideoAd loadAdData];
}
//打开激励视频的方法
-(void) OpenAd{
if(self.rewardedVideoAd.isAdValid){
[self.rewardedVideoAd showAdFromRootViewController:self];
}
}
/**
This method is called when video ad material loaded successfully.
*/
- (void)nativeExpressRewardedVideoAdDidLoad:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
NSLog(@"----------此方法在成功加载视频广告素材时调用。");
}
/**
This method is called when video ad materia failed to load.
@param error : the reason of error
*/
- (void)nativeExpressRewardedVideoAd:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *_Nullable)error{
NSLog(@"----------当视频广告材料加载失败时调用此方法。error.code = %l",error.code);
}
/**
This method is called when cached successfully.
*/
- (void)nativeExpressRewardedVideoAdDidDownLoadVideo:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
NSLog(@"----------成功缓存时调用此方法。");
}
/**
This method is called when rendering a nativeExpressAdView successed.
*/
- (void)nativeExpressRewardedVideoAdViewRenderSuccess:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
NSLog(@"----------在成功呈现nativeExpressAdView时调用此方法。");
}
/**
This method is called when a nativeExpressAdView failed to render.
@param error : the reason of error
*/
- (void)nativeExpressRewardedVideoAdViewRenderFail:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd error:(NSError *_Nullable)error{
NSLog(@"----------当nativeExpressAdView无法呈现时调用此方法。error.code = %l",error.code);
}
/**
This method is called when video ad slot will be showing.
*/
- (void)nativeExpressRewardedVideoAdWillVisible:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
NSLog(@"----------此方法在显示视频广告槽时调用。");
}
/**
This method is called when video ad slot has been shown.
*/
- (void)nativeExpressRewardedVideoAdDidVisible:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
NSLog(@"----------此方法在显示视频广告槽时调用。");
}
/**
This method is called when video ad is about to close.
*/
- (void)nativeExpressRewardedVideoAdWillClose:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
NSLog(@"----------此方法在视频广告即将关闭时调用。");
}
/**
This method is called when video ad is closed.
*/
- (void)nativeExpressRewardedVideoAdDidClose:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
NSLog(@"----------此方法在视频广告关闭时调用。");
// NSLog(@"-----------nativeExpressRewardedVideoAdDidClose");
// 调用 js/ts 脚本中的函数: AppMain 节点下 IOSCtrl 脚本中的 GetAward 的函数。
[CallJS callJsCCNodeFunc_1:@"视屏广告看完了,发奖励罗!"];
//视频结束后,再加载一次广告数据,保证广告的不重复
[self.rewardedVideoAd loadAdData];
}
- (void)testCallJs{
// 调用 js/ts 脚本中的函数: AppMain 节点下 IOSCtrl 脚本中的 GetAward 的函数。
[CallJS callJsCCNodeFunc_1:@"第1个参数!"];
// 调用 js/ts 脚本中的函数: AppMain 节点下 IOSCtrl 脚本中的 GetAward2 的函数。
[CallJS callJsCCNodeFunc_3:@"GetAward2" withCmd:@"第1个参数!" withContent:@"第2个参数!"];
// 调用 js/ts 的全局函数:GetBigAward
[CallJS callJsGlobalFunc_2:@"GetBigAward" withCmd:@"第1个参数!"];
}
/**
This method is called when video ad is clicked.
*/
- (void)nativeExpressRewardedVideoAdDidClick:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
NSLog(@"----------此方法在单击视频广告时调用。");
}
/**
This method is called when the user clicked skip button.
*/
- (void)nativeExpressRewardedVideoAdDidClickSkip:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
NSLog(@"----------此方法在单击视频广告时调用。");
}
/**
This method is called when video ad play completed or an error occurred.
@param error : the reason of error
*/
- (void)nativeExpressRewardedVideoAdDidPlayFinish:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *_Nullable)error{
NSLog(@"----------此方法在视频广告播放完成或发生错误时调用。error.code = %l",error.code);
}
/**
Server verification which is requested asynchronously is succeeded.
@param verify :return YES when return value is 2000.
*/
- (void)nativeExpressRewardedVideoAdServerRewardDidSucceed:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd verify:(BOOL)verify{
NSLog(@"----------异步请求的服务器验证成功。");
}
/**
Server verification which is requested asynchronously is failed.
Return value is not 2000.
*/
- (void)nativeExpressRewardedVideoAdServerRewardDidFail:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
NSLog(@"----------异步请求的服务器验证失败。");
}
@end
首先在 AppController 类定义与实现 csjAdRewardOpen
// object-c 看视屏函数,在 js/ts 中调用。
+ (void)csjAdRewardOpen:(NSString *)code{
NSLog(@"----- js/ts 调用了 object-c 函数 --打开激励视频");
[[CsjAdReward getAdInstance] OpenAd];
}
查看 CsjAdReward 脚本函数 nativeExpressRewardedVideoAdDidClose
/**
This method is called when video ad is closed.
*/
- (void)nativeExpressRewardedVideoAdDidClose:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
NSLog(@"----------此方法在视频广告关闭时调用。");
// NSLog(@"-----------nativeExpressRewardedVideoAdDidClose");
// 调用 js/ts 脚本中的函数: AppMain 节点下 IOSCtrl 脚本中的 GetAward 的函数。
[CallJS callJsCCNodeFunc_1:@"视屏广告看完了,发奖励罗!"];
//视频结束后,再加载一次广告数据,保证广告的不重复
[self.rewardedVideoAd loadAdData];
}
有关 CallJS 类的实现见如下代码(类的文件名字注意是 CallJS.mm,如果是CallJS.m 请在xcode编辑器中修改过来)
#import
#import "cocos2d.h"
#import "CallJS.h"
// 这个必须导入,否则报错。
#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
//using namespace std;
@implementation CallJS
+(void)callJsCCNodeFunc_1:(NSString*) cmdStr{
NSLog(@"-------callJsCCNodeFunc_1...");
std::string param001 = [cmdStr UTF8String];
// "cc.find('AppMain').getComponent('IOSCtrl').GetAward(\"%s\");", param001.c_str()
// 可以理解为:调用 cc.find() 函数在场景中查找 AppMain 节点,在利用 getComponent() 函数获取该节点下 名为 IOSCtrl.ts 的脚本。最后调用 脚本中的成员函数 GetAward(),此函数有一个参数。
std::string jsCallStr = cocos2d::StringUtils::format("cc.find('AppMain').getComponent('IOSCtrl').GetAward(\"%s\");", param001.c_str());
NSLog(@"--------- jsCallStr = %s", jsCallStr.c_str());
se::ScriptEngine::getInstance()->evalString(jsCallStr.c_str());
}
+(void)callJsCCNodeFunc_3:(NSString*) funcNameStr withCmd:(NSString*) cmdStr withContent:(NSString*) contentStr{
NSLog(@"-------callJsCCNodeFunc_3...");
std::string funcName = [funcNameStr UTF8String];
std::string param001 = [cmdStr UTF8String];
std::string param002 = [contentStr UTF8String];
std::string jsCallStr = cocos2d::StringUtils::format("cc.find('AppMain').getComponent('IOSCtrl').%s(\"%s\",\"%s\");", funcName.c_str(),param001.c_str(),param002.c_str());
NSLog(@"--------- jsCallStr = %s", jsCallStr.c_str());
se::ScriptEngine::getInstance()->evalString(jsCallStr.c_str());
}
+(void)callJsGlobalFunc_1:(NSString*) funcNameStr{
NSLog(@"-------callJsGlobalFunc_1...");
std::string funcName = [funcNameStr UTF8String];
std::string jsCallStr = cocos2d::StringUtils::format("%s();",funcName.c_str());
NSLog(@"--------- jsCallStr = %s", jsCallStr.c_str());
se::ScriptEngine::getInstance()->evalString(jsCallStr.c_str());
}
+(void)callJsGlobalFunc_2:(NSString*) funcNameStr withCmd:(NSString*) cmdStr{
NSLog(@"-------callJsGlobalFunc_2...");
std::string funcName = [funcNameStr UTF8String];
std::string param001 = [cmdStr UTF8String];
std::string jsCallStr = cocos2d::StringUtils::format("%s(\"%s\");",funcName.c_str(), param001.c_str());
NSLog(@"--------- jsCallStr = %s", jsCallStr.c_str());
se::ScriptEngine::getInstance()->evalString(jsCallStr.c_str());
}
+(void)callJsGlobalFunc_3:(NSString*) funcNameStr withCmd:(NSString*) cmdStr withContent:(NSString*) contentStr{
NSLog(@"-------callJsGlobalFunc_3...");
std::string funcName = [funcNameStr UTF8String];
std::string param001 = [cmdStr UTF8String];
std::string param002 = [contentStr UTF8String];
std::string jsCallStr = cocos2d::StringUtils::format("%s(\"%s\",\"%s\");",funcName.c_str(), param001.c_str(),param002.c_str());
NSLog(@"--------- jsCallStr = %s", jsCallStr.c_str());
// ScriptingCore::getInstance()->evalString(jsCallStr.c_str());
se::ScriptEngine::getInstance()->evalString(jsCallStr.c_str());
}
@end
有关 CocosCreator 中的ts脚本IOSCtrl.ts。如下:
const { ccclass, property } = cc._decorator;
/**
* 这里是一个全局函数,函数名为 GetBigAward ,带有一个参数。
* 可供 object-c 调用 js/ts 用。
*/
window["GetBigAward"] = function(code:string){
console.error("------ object-c 调用 js 全局函数,参数 code = ",code);
}
/**
* 与 Ios object-c 交互
* 此脚本 绑定在 游戏中景中 AppMain 节点下,可以通过 cc.find('AppMain');语句找到此节点。
*/
@ccclass
export class IOSCtrl extends cc.Component {
onLoad(){
console.log("------ IOSCtrl onLoad");
// this.AddListener();
}
onDestroy(){
// this.RemoveListener();
}
// private AddListener(){
// Messenger.AddListener(MsgEvent.CSJSDK_IOS_LookVideo,this.LookVideo,this);
// Messenger.AddListener(MsgEvent.CSJSDK_IOS_ShowBanner,this.ShowBanner,this);
// Messenger.AddListener(MsgEvent.CSJSDK_IOS_HideBanner,this.HideBanner,this);
// }
// private RemoveListener(){
// Messenger.RemoveListener(MsgEvent.CSJSDK_IOS_LookVideo,this.LookVideo,this);
// Messenger.RemoveListener(MsgEvent.CSJSDK_IOS_ShowBanner,this.ShowBanner,this);
// Messenger.RemoveListener(MsgEvent.CSJSDK_IOS_HideBanner,this.HideBanner,this);
// }
/**
* js/ts 调用 object-c 用。
*/
private LookVideo():void{
if ('jsb' in window) {
if (cc.sys.os == cc.sys.OS_IOS) {
console.error("------- js 调用 object-c 去 看视频 ");
// js 调用 object-c 中 AppController 类中的 静态函数 csjAdRewardOpen ,带有一个参数。
// 注意 函数名必须带上 ":" ,否则无法找到 函数。 如 "csjAdRewardOpen:"
jsb.reflection.callStaticMethod("AppController", "csjAdRewardOpen:","参数1");
// 如果在 object-c 把函数定义成这个样子:+ (void)csjAdRewardOpen:(NSString *)code withcmd:(NSString *)code2;
// 那么调用时函数名必须写成 "csjAdRewardOpen:withcmd:"
// jsb.reflection.callStaticMethod("AppController", "csjAdRewardOpen:withcmd:","参数1","参数2");
}
}
}
/**
* js/ts 调用 object-c 用。
*/
private ShowBanner():void{
if ('jsb' in window) {
if (cc.sys.os == cc.sys.OS_IOS) {
console.error("------- js 调用 object-c 去 csjAdShowBanner ");
jsb.reflection.callStaticMethod("AppController", "csjAdShowBanner:","2222");
}
}
}
/**
* js/ts 调用 object-c 用。
*/
protected HideBanner():void{
if ('jsb' in window) {
if (cc.sys.os == cc.sys.OS_IOS) {
console.error("------- js 调用 object-c 去 csjAdHideBanner ");
jsb.reflection.callStaticMethod("AppController", "csjAdHideBanner:","3333");
}
}
}
/**
* 可供 object-c 调用 js/ts 用。
*/
public GetAward(code:string){
console.error("------ object-c 调用了 js 返回了视屏奖励,code =",code)
// let mon = Platform.instance.platformHadler as CSJSDKPlatform;
// if(mon){
// CSJSDKPlatform.IOSGetRewardVideo();
// }
}
/**
* 可供 object-c 调用 js/ts 用。
* @param code
* @param code2
*/
public GetAward2(code:string,code2:string){
console.error("------ object-c 调用了 js 返回了视屏奖励,code =",code,",code2 = ",code2)
// let mon = Platform.instance.platformHadler as CSJSDKPlatform;
// if(mon){
// CSJSDKPlatform.IOSGetRewardVideo();
// }
}
}