Adding Code to the AppDelegate

Hello!

I’m trying to add code to my AppDelegate. But I am not sure where to do it - and how exactly.

I am trying to achieve Deep Linking, so I am trying to add my code, which adds a global variable ’

window.customMissionIDOverride = 'MI-xxxx-3xxx';

(which I’m planning to overwrite with a URL parameter, derived from an URL like

escape-team://mission/MI-xxxx-3xxx

that the user can access via a QR code) to my AppDelegate.cpp:

/****************************************************************************
 Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.

 http://www.cocos.com

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated engine source code (the "Software"), a limited,
 worldwide, royalty-free, non-assignable, revocable and non-exclusive license
 to use Cocos Creator solely to develop games on your target platforms. You shall
 not use Cocos Creator software for developing other software or tools that's
 used for developing games. You are not granted to publish, distribute,
 sublicense, and/or sell copies of Cocos Creator.

 The software or tools in this License Agreement are licensed, not sold.
 Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

#include "AppDelegate.h"

#include "cocos2d.h"

#include "cocos/scripting/js-bindings/manual/jsb_module_register.hpp"
#include "cocos/scripting/js-bindings/manual/jsb_global.h"
#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
#include "cocos/scripting/js-bindings/event/EventDispatcher.h"
#include "cocos/scripting/js-bindings/manual/jsb_classtype.hpp"

USING_NS_CC;
#ifdef SDKBOX_ENABLED
#include "PluginIAPJS.hpp"
#include "PluginIAPJSHelper.h"
#endif
#ifdef SDKBOX_ENABLED
#include "PluginReviewJS.hpp"
#include "PluginReviewJSHelper.h"
#endif

AppDelegate::AppDelegate(int width, int height) : Application("Cocos Game", width, height)
{
}

AppDelegate::~AppDelegate()
{
}



bool AppDelegate::applicationDidFinishLaunching()
{
    se::ScriptEngine* se = se::ScriptEngine::getInstance();

    jsb_set_xxtea_key("7d334562-0879-4b");
    jsb_init_file_operation_delegate();

#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0)
    // Enable debugger here
    jsb_enable_debugger("0.0.0.0", 6086, false);
#endif

    se->setExceptionCallback([](const char* location, const char* message, const char* stack){
        // Send exception information to server like Tencent Bugly.
        cocos2d::log("\nUncaught Exception:\n - location :  %s\n - msg : %s\n - detail : \n      %s\n", location, message, stack);
    });

    jsb_register_all_modules();
#ifdef SDKBOX_ENABLED
    se->addRegisterCallback(register_all_PluginIAPJS);
    se->addRegisterCallback(register_all_PluginIAPJS_helper);
#endif
#ifdef SDKBOX_ENABLED
    se->addRegisterCallback(register_all_PluginReviewJS);
    se->addRegisterCallback(register_all_PluginReviewJS_helper);
#endif

    se->start();

    
    se::AutoHandleScope hs;
    jsb_run_script("jsb-adapter/jsb-builtin.js");


    se::ScriptEngine::getInstance()->evalString("console.log('applicationDidFinishLaunching');");


    jsb_run_script("main.js");

    
    se->addAfterCleanupHook([](){
        JSBClassType::destroy();
    });

    return true;
}


bool AppDelegate::applicationDidFinishLaunchingWithOptions()
{
    se::ScriptEngine::getInstance()->evalString("console.log('Checkpoint applicationDidFinishLaunchingWithOptions');");
    se::ScriptEngine::getInstance()->evalString("window.customMissionIDOverride = 'MI-xxxx-3xxx';");
    
    
    return true;
}




// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::onPause()
{
    EventDispatcher::dispatchOnPauseEvent();
}

// this function will be called when the app is active again
void AppDelegate::onResume()
{
    EventDispatcher::dispatchOnResumeEvent();
}

Unfortunately,

 bool AppDelegate::applicationDidFinishLaunchingWithOptions()

never gets run, also not when I launch my app via the URL (which launches the app, but not AppDelegate::applicationDidFinishLaunchingWithOptions())

I also tried adding

app->se::ScriptEngine::getInstance()->evalString("console.log('didFinishLaunchingWithOptions (AppController.mm)');");
    app->se::ScriptEngine::getInstance()->evalString("window.customMissionIDOverride = 'MI-xxxx-3xxx';");

to my AppController.mm, but here I cannot access app->se…:

This is my AppController.mm:

/****************************************************************************
 Copyright (c) 2010-2013 cocos2d-x.org
 Copyright (c) 2013-2016 Chukong Technologies Inc.
 Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
 
 http://www.cocos2d-x.org
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

#import "AppController.h"
#import "cocos2d.h"
#import "AppDelegate.h"
#import "RootViewController.h"
#import "SDKWrapper.h"
#import "platform/ios/CCEAGLView-ios.h"



using namespace cocos2d;

@implementation AppController

Application* app = nullptr;
@synthesize window;

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[SDKWrapper getInstance] application:application didFinishLaunchingWithOptions:launchOptions];


    NSDictionary *activityDictionary = launchOptions[UIApplicationLaunchOptionsUserActivityDictionaryKey];
        if (activityDictionary) {
      
            printf("activityDictionary");
            
            // Here we can detect the Universal Link URL
            NSUserActivity *activity = [activityDictionary objectForKey:@"UIApplicationLaunchOptionsUserActivityKey"];
            NSString *urlString = activity.webpageURL.absoluteString;
            NSURL *url = [NSURL URLWithString:urlString];
            
            printf("%s \n", urlString);

            
        }


    // Add the view controller's view to the window and display.
    float scale = [[UIScreen mainScreen] scale];
    CGRect bounds = [[UIScreen mainScreen] bounds];
    window = [[UIWindow alloc] initWithFrame: bounds];
    
    // cocos2d application instance
    app = new AppDelegate(bounds.size.width * scale, bounds.size.height * scale);
    app->setMultitouch(true);

    
    app->se::ScriptEngine::getInstance()->evalString("console.log('didFinishLaunchingWithOptions (AppController.mm)');");
    app->se::ScriptEngine::getInstance()->evalString("window.customMissionIDOverride = 'MI-xxxx-3xxx';");
    
    
    // Use RootViewController to manage CCEAGLView
    _viewController = [[RootViewController alloc]init];
#ifdef NSFoundationVersionNumber_iOS_7_0
    _viewController.automaticallyAdjustsScrollViewInsets = NO;
    _viewController.extendedLayoutIncludesOpaqueBars = NO;
    _viewController.edgesForExtendedLayout = UIRectEdgeAll;
#else
    _viewController.wantsFullScreenLayout = YES;
#endif
    // Set RootViewController to window
    if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)
    {
        // warning: addSubView doesn't work on iOS6
        [window addSubview: _viewController.view];
    }
    else
    {
        // use this method on ios6
        [window setRootViewController:_viewController];
    }
    
    [window makeKeyAndVisible];
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    
    //run the cocos2d-x game scene
    app->start();
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
    app->onPause();
    [[SDKWrapper getInstance] applicationWillResignActive:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
    app->onResume();
    [[SDKWrapper getInstance] applicationDidBecomeActive:application];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
    [[SDKWrapper getInstance] applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
    [[SDKWrapper getInstance] applicationWillEnterForeground:application];    
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    [[SDKWrapper getInstance] applicationWillTerminate:application];
    delete app;
    app = nil;
}


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}

@end


Any thoughts on this would be fantastic. Thank you!

se::ScriptEngine::getInstance() is a static method and does not require the use of the app object. You can use se::ScriptEngine::getInstance()->evalString("") directly

Also, in AppDelegate, is it possible to add code in the start function?

In version 3.5, AppDelegate.mm will be placed inside the engine. Most of the functions can be achieved through game.cpp. A simpler interface is also implemented. For example, you can use the interface runScript(“window.customMissionIDOverride = ‘MI-xxxx-3xxx’;”) directly in the onStart callback in game.cpp.

Thanks, I will try that!

I am using 2.4.5.

One more question:

When I build my project in Cocos Creator, my

AppController.mm
etc.

files are copied from somewhere to the build folder. But from where? I want to edit these files and not lose my changes when I rebuild my project.

Thank you!
Fabian

Reference local path: engine-root-path(yourself) /templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios

How do I find my engine root path?

Is the path of the source code

image

My project folder does not have a templates subfolder?

Sorry, I forgot that you may not have cloned the code locally from github.
In this case, the root path of the engine is in the dashboard’s installation directory:
E.g:
/root directory/dashboard installation path/Creator/Cocos creator version(2.4.5)/resources/cocos2d-x/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios

Note that the paths may be different for different versions. The following uses version 2.4.5 as an example. Different system paths are also somewhat different.

E.g:
The path for Windows is:
D:\CocosDashboard\resources.editors\Creator\2.4.5\resources\cocos2d-x\templates\js-template-default\frameworks\runtime-src\proj.ios_mac\ios

The path on Mac is
/Applications/CocosCreator/Creator/2.4.5/CocosCreator.app/Contents/Resources/cocos2d-x/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios

You can also view the path of cocos creator in the dashboard
Windows:


Mac: