CocosCreator接入穿山甲SDK(IOS)--激勵視屏

參考

環境: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

穿山甲SDK初始化

在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];

接入激勵視屏。

定義 Object-C 頭文件,CsjAdReward.h

代碼如下:

@interface CsjAdReward  : UIViewController{
//    int countNum;
}
+(CsjAdReward *) getAdInstance;            //用來獲取實例的方法
-(void) OpenAd;
-(void) testCallJs;
@end

實現 Object-C CsjAdReward 類

代碼如下:


#import <Foundation/Foundation.h>
#import "CsjAdReward.h"
#import <BUAdSDK/BURewardedVideoModel.h>
#import <BUAdSDK/BUNativeExpressRewardedVideoAd.h>
//#import <BUAdSDK/BURewardedVideoAd.h>
//#import "AppController.h"
#import <BUAdSDK/BUAdSDKManager.h>
//
#import "CallJS.h"
//#import "RootViewController.h"
@interface CsjAdReward ()<BUNativeExpressRewardedVideoAdDelegate>
@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

如何在 CocosCreator 中調用

首先在 AppController 類定義與實現 csjAdRewardOpen

//  object-c 看視屏函數,在 js/ts 中調用。
+ (void)csjAdRewardOpen:(NSString *)code{
    NSLog(@"----- js/ts 調用了 object-c 函數 --打開激勵視頻");
    
   [[CsjAdReward getAdInstance] OpenAd];
}

如何將看完視屏的結果返回給CocosCreator

查看 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 <Foundation/Foundation.h>

#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();
        // }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章