I’m writing a Javascript class that passes a function with one parameter to an Objective-C class (Using the NimbleKit framework). It does this like so:
NKRegisterClass("SKGetEvents");
// TEMP Test date sent to the NKitAction, won't be hardcoded
var testDate = "2011-10-14";
var goButton = new NKButton();
goButton.init(100,20,100,50,"callGetEvents(testDate)"); /*Button to launch function */
goButton.setTitle("Get Events");
goButton.show();
function callGetEvents(testDate) {
CallNKitAction("GetEventsFunction?className=SKGetEvents&dateStringInput="+testDate);
}
So it will call an registered Objective-C class function using CallNKitAction, passing a
javascript string (in this case var testDate = “2011-10-14”) as the argument.
The responding function in the Objective-C class doesn’t get called at all. It looks like this:
-(NSString *) GetEventsFunction:(const char *)dateStringInput {
// Do stuff with date passed }
If I change the function to take no arguments and just hardcode a date inside that, the function is called fine and works. This tells me the issue is trying to pass the JS var as a (const char *) is the problem. I have no idea how else to call that into the function and then convert it to an NSString for use, so far I’ve tried just passing the string as an NSString, const char and converting that to NSString using StringWithUTF8String, all to no avail.
Sorry for the long explanation, but does anyone have any ideas on how this could be achieved? (Have also asked on their forums but not a very big community so posting here too.) Help will be much appreciated.
In case anyone else needs to know, I’m adding how I solved this very old question:
NimbleKit does allow for the passing of as many parameters as needed from Javascript to Objective-C, through some inbuilt parameter methods that are stored in an NSDictionary. It even allows a simple one-liner to return an result back to the calling Javascript function!
The Javascript side is fine as it is (unless you want to get a result, more on that below), but to the target Objective-C class, add the following to the header:
And also add the following methods to the bottom of the class implementation:
Now to use these functions, here’s an example which can receive a resulting NSString from the iOS class! First the Javascript:
And now the Objective-C class (note the return type is void and it accepts no parameters in the typical sense, this is because they are passed in/returned differently):
And there you go, not only passing objects to Objective-C from Javascript with NimbleKit, but even returning results for Javascript to use as well! For more resources along these lines, there’s a great project that sprung up on the NimbleKit forums which covers a lot of hybrid JS/iOS functionality here.