Adding code to my AppDelegate / AppController

477 views Asked by At

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!

Update

I think I'm almost there.

I have four files that I'm working with now:

AppController.h


#import <UIKit/UIKit.h>

@class RootViewController;

@interface AppController : NSObject <UIApplicationDelegate>
{
}

@property(nonatomic, readonly) RootViewController* viewController;

@end


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 *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    
    
    
    NSLog(@"escapeteam: Launching with options");

    id sendingAppID
    = [options objectForKey: UIApplicationOpenURLOptionsSourceApplicationKey];
    
    if (sendingAppID) {
        NSLog(@"escapeteam: source application = %@", sendingAppID);
    }
    
    NSURLComponents *components
    = [[NSURLComponents alloc] initWithURL: url resolvingAgainstBaseURL: YES];
    
    NSString *albumPath = components.path;
    
    NSString *missionPath = components.path;
    
    NSArray *params = components.queryItems;
    
    if (!components && !missionPath && !albumPath && !params) {
        NSLog(@"escapeteam: Invalid URL or mission path missing");
        return NO;
    }

    NSLog(@"escapeteam: mission = %@", params.firstObject);

   // self.missionId = params.firstObject;
    app->setMissionId();
    

    NSUInteger photoIndex = [params indexOfObjectPassingTest:^BOOL(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSURLQueryItem *queryItem = (NSURLQueryItem*) obj;
        return [queryItem.name isEqual: @"index"];
    }];
    
    
/*    NSString *missionId = [params indexOfObjectPassingTest:^BOOL(id  _Nonnull obj, NSString *idx, BOOL * _Nonnull stop) {
        NSURLQueryItem *queryItem = (NSURLQueryItem*) obj;
        return [queryItem.name isEqual: @"index"];
    }];
  */
    
    
    if (photoIndex != NSNotFound) {
        
        NSURLQueryItem *queryItem = [params objectAtIndex: photoIndex];
        NSString *photoIndex = queryItem.value;
        
        NSLog(@"escapeteam: mission = %@", missionPath);
        NSLog(@"escapeteam: albumPath = %@", albumPath);
        NSLog(@"escapeteam: photoIndex = %@", photoIndex);
        return YES;
        
    }
    
    NSLog(@"Photo index missing");
    return NO;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[SDKWrapper getInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    
    NSLog(@"escapeteam: Launch without options");

    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


AppDelegate.h

/****************************************************************************
 Copyright (c) 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.
 ****************************************************************************/
#pragma once

#include "platform/CCApplication.h"
/**
 @brief    The cocos2d Application.
 
 The reason for implement as private inheritance is to hide some interface call by Director.
 */
class  AppDelegate : public cocos2d::Application
{
public:
    AppDelegate(int width, int height);
    virtual ~AppDelegate();
    
    /**
     @brief    Implement Director and Scene init code here.
     @return true    Initialize success, app continue.
     @return false   Initialize failed, app terminate.
     */
    virtual bool applicationDidFinishLaunching() override;
    virtual bool applicationDidFinishLaunchingWithOptions();
    
    
   virtual void setMissionId();

    /**
     @brief  The function be called when the application is paused
     */
    virtual void onPause() override;
    
    /**
     @brief  The function be called when the application is resumed
     */
    virtual void onResume() override;


};

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("window.your_func('put string here')");


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

    jsb_run_script("main.js");

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

    return true;
}




void AppDelegate::setMissionId()
{
    cocos2d::log("setMissionId###########");
    se::ScriptEngine::getInstance()->evalString("window.customMissionIDOverride = 'MI-xxxx-3xxx';");
    
    
}

bool AppDelegate::applicationDidFinishLaunchingWithOptions()
{
    
 
    cocos2d::log("didFinishLaunchingWithOptions###########");
    
    
    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();
}

Here's what I figured out:

The app gets launched with an argument, and first

NSLog(@"escapeteam: Launch without options");

is run (I see the log). That initiates also the

app

object in the AppController's scope, which is what I want to access.

It does so by instantiating an AppDelegate:

    app = new AppDelegate(bounds.size.width * scale, bounds.size.height * scale);

... however, I fail to add my new function

virtual void setMissionId();

to it, despite declaring it in the .h file and implementing it in the .cpp file:



void AppDelegate::setMissionId()
{
    cocos2d::log("setMissionId###########");
    se::ScriptEngine::getInstance()->evalString("window.customMissionIDOverride = 'MI-xxxx-3xxx';");
    
    
}

– the error I get for

app->setMissionId();

is this:

'UIApplication' does not have a member named 'setMissionId'

... which is, I guess, true - UIApplication doesn't have that method, but I can't access the method I defined in the AppDelegate.

Any help is appreciated, thank you!

1

There are 1 answers

3
Shawn Frank On

Here is how you can add application:openURL:options: to your AppDelegate and create a property that can be accessed outside the AppDelegate

First, in your AppDelegate.h

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

// This instance variable can be accessed publicly
// This example sets photoIndex as a property
// But you can create a property for anything you
// want to access publicly
@property NSString *photoIndex;

@end

Then, your AppDelegate.m looks like this

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    return YES;
}


#pragma mark - UISceneSession lifecycle


- (UISceneConfiguration *)application:(UIApplication *)application
configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession
                              options:(UISceneConnectionOptions *)options {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration"
                                          sessionRole:connectingSceneSession.role];
}


- (void)application:(UIApplication *)application
didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
    
}

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    
    id sendingAppID
    = [options objectForKey: UIApplicationOpenURLOptionsSourceApplicationKey];
    
    if (sendingAppID) {
        NSLog(@"source application = %@", sendingAppID);
    }
    
    NSURLComponents *components
    = [[NSURLComponents alloc] initWithURL: url resolvingAgainstBaseURL: YES];
    
    NSString *albumPath = components.path;
    
    NSArray *params = components.queryItems;
    
    if (!components && !albumPath && !params) {
        NSLog(@"Invalid URL or album path missing");
        return NO;
    }
    
    NSUInteger photoIndex = [params indexOfObjectPassingTest:^BOOL(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSURLQueryItem *queryItem = (NSURLQueryItem*) obj;
        return [queryItem.name isEqual: @"index"];
    }];
    
    if (photoIndex != NSNotFound) {
        
        NSURLQueryItem *queryItem = [params objectAtIndex: photoIndex];
        self.photoIndex = queryItem.value;
        
        NSLog(@"albumPath = %@", albumPath);
        NSLog(@"photoIndex = %@", self.photoIndex);
        return YES;
        
    }
    
    NSLog(@"Photo index missing");
    return NO;
}

@end

This is how you can then access the instance variable from the AppDelegate

// You need to have this import at the top of your file 
// before using the below code
#import "AppDelegate.h"

// Then in some function
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

// Do what you want with the variable
NSLog(@"%@", appDelegate.photoIndex);