Call method in AppController.m from scene

I’d like to call a method in AppController.m from HelloWorldScene.cpp Is this possible? So in my AppController.m I have the following:

- (void) showReviewPrompt {
    [Appirater tryToShowPrompt];
}

And in HelloWorldScene I am trying to do:

AppController *appController = (AppController *)[[UIApplication sharedApplication] delegate];
[appController showReviewPrompt];

I get an undeclared identifier error for AppController and when I try to import it I get even more errors.

yeah, you can’t just online objective-c and c++ like that. At a minimum you would need to change some build settings to even accomplish that.

I think what you need is called a “wrapper” class. Basically, an extra class in between to handle communication.

What you need to do is to create a header for your wrapper class that contains no Objective-C code, and will probably declare a static function that will call the Objective-C code. Then your wrapper class file (.mm; needs to be an Objective-C file) will include your header file and AppController.h, and implement your static function, which will call your function in AppController. For example:

// AppControllerWrapper.hpp
// NO OBJECTIVE-C CODE
class AppControllerWrapper {
public:
    static void showReviewPrompt();
};

// AppControllerWrapperIOS.mm
// CONTAINS OBJECTIVE-C CODE
#include "AppControllerWrapper.h"
#include "AppController.h"

void AppControllerWrapper::showReviewPrompt() {
    AppController *appController = (AppController *)[[UIApplication sharedApplication] delegate];
    [appController showReviewPrompt];
}

// HelloWorldScene.cpp
#include "AppControllerWrapper.hpp"
...
AppControllerWrapper::showReviewPrompt(); // inside a function

I tested this and it seems to work.

So, basically, your C++ classes can’t contain any Objective-C, which includes using headers that contain any Objective-C, but because you can mix C++ and Objective-C, you can create a C+±style header for your C++ class to include and then call your Objective-C code from the class file.

Note: If you want to run your app on platforms other than iOS and Mac, you will need to make sure you don’t include your .mm for those platforms (which is why I called it AppControllerIOS.mm) and implement the class for your platform as a C++ file.

1 Like

Can I use some of your post in our docs?

Sure thing. Spread the knowledge!