I've been thinking of a way to implement In App Purchases in TVML apps.
Is there a way you could fire an event back to the Swift/Obj C app and let StoreKit take over control?
I managed to handle this in Objective-C. I've made an actual implementation here, but here's a sample of what it might look like:
First let's take a look at the header file:
// MyClass.h
#import <JavaScriptCore/JavaScriptCore.h> // This is where JSExport lies
/*
* This is where the magic happens. Any method declared inside a JSExport protocol
* will be translated into JavaScript. Quite useful.
*/
@protocol MyClassJavascriptMethods <JSExport>
- (BOOL) method;
- (NSString*) methodWithAnArgument:(NSDictionary*)argument;
@end
/*
* This class must implement the above protocol
*/
@interface MyClass : NSObject <..., MyClassJavaScriptMethods>
@endNotice the protocol, it's where the Obj-C - JS binding actually happens. Now let's move over to the implementation file:
// MyClass.m
#import "MyClass.h"
@implementation MyClass
// implement the MyClassJavascriptMethods protocol:
- (BOOL) method {
// do stuff
}
- (NSString*) methodWithAnArgument:(NSDictionary*)argument {
// do some other stuff
}
@endNow go to your TVApplicationControllerDelegate:
#import "MFInAppPurchaseManager.h"
// make a property to prevent ARC from destroying your object
@property (strong) MyClass* myClassObject;
-(void)appController:(TVApplicationController *)appController evaluateAppJavaScriptInContext:(JSContext *)jsContext {
MyClass *createdObject = [[MyClass alloc] init];
self.myClassObject = createdObject;
[jsContext setObject:createdObject forKeyedSubscript:@"mySuperCoolObject"]; // mySuperCoolObject will be your object's name in JS
}The last thing to do is to go to your JavaScript file, where mySuperCoolObject is now a global variable:
mySuperCoolObject.method();
mySuperCoolObject.methodWithAnArgument(someArgument);And that's pretty much it!