Skip to content

Instantly share code, notes, and snippets.

@phuochau
Last active April 11, 2018 23:40
Show Gist options
  • Save phuochau/ade9136fafaf4adfb76fb82342ea25be to your computer and use it in GitHub Desktop.
Save phuochau/ade9136fafaf4adfb76fb82342ea25be to your computer and use it in GitHub Desktop.
Using callback from Objective-C to Cocoascript

Re-build cocoa framework

  • Clone source code from: https://github.com/ccgus/CocoaScript
  • Make MOJavascriptObject.h as public headers in Build Phases
  • Build project and we will get CocoaScript.framework
  • Copy CocoaScript.framework to your Xcode project

Define the objective-c methods with callback

API.h

#import <Foundation/Foundation.h>
#import <CocoaScript/MOJavaScriptObject.h>
#import <CocoaScript/COScript.h>

@interface Api : NSObject
- (void) login:(NSDictionary*)params onComplete:(MOJavaScriptObject*)onComplete;
@end

API.m

- (void) login:(NSDictionary*) params onComplete:(MOJavaScriptObject*)onComplete {
  // handle your logic
  
  // call the callback
   COScript *script = [[COScript alloc] init];
  [script callJSFunction:[onComplete JSObject] withArgumentsInArray:@[@true, @{@"name": @"Sam"}]];
}

Using in .cocoascript

var api = API.alloc().init();
api.login({
  username: 'sam',
  password: '123456'
}, function (success, user) {
  log(success);
  log(user);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment