OpenAphid-Engine 0.2 was shipped with a new binding system which can bridge JavaScript functions to Objective-C methods on demand. It’s useful for games to integrate analytics services, monetization solutions, and social services, etc. In this tutorial, we’ll go through the binding system by demonstrating how to integrate Google Analytics iOS SDK into OpenAphid-Engine.

How to Access Objective-C Methods in JavaScript

The OABindingProtocol protocol, defined in OABindingProtocol.h, defines a method bindSelectors: that you can implement in your Objective-C classes to expose their methods to the JavaScript environment. To make a method valid for export, its return type and all argument types must be the supported types below:

Type Conversion of Return Value from Objective-C to JavaScript

Objective-C

JavaScript

void

undefined

nil or NSNull

null

primitive numeric types(int, float, double, etc)

number

NSNumber

number

NSString

string

NSArray

array

NSDictionary

object

Type Conversion of Argument Value from JavaScript to Objective-C

JavaScript

Objective-C

undefined

nil or NSNull

null

nil or NSNull

number

primitive number or NSNumber

string

NSString

array

NSArray

object except array

NSDictionary

For any method to export, it must be explicitly declared in the implementation of bindSelectors: in your Objective-C class. For example, the snippet below exports [DatastoreBinding saveString:] to JavaScript environment as int saveString(string):

OpenAphid-Engine injects an instance of DatastoreBinding as a JavaScript object of [object DynamicBinding] into JavaScript environment. And its name is datastore. The iOSOnly argument manages the namespace which contains the injected object. If it’s YES, then the injected object can be accessed via aphid.extios.datastore; otherwise it can be accessed via aphid.ext.datastore.

Notes: the iOSOnly argument is actually designed for future compliance when OpenAphid-Engine supports both iOS and Android.

Integration with Google Analytics in Boilerplate-iOS

Let’s see a more concrete example about integrating Google Analytics in Boilerplate-iOS.