新項目需要在app游戲大廳中集成眾多小游戲
仍然使用creator開發
然而若發布h5版本,用戶首次加載時間相對較長
因此首批打算將游戲集成在app中,發布原生版本
這里總結一下ios原生版本開發過程中js與oc的互相調用方法
轉載請標明原文地址:http://www.cnblogs.com/billyrun/articles/8529503.html
js調用oc
參考官方文檔Objective-C 原生反射機制
在ios工程中聲明定義一個靜態方法供js調用
在.h文件中聲明函數showAd
#import <UIKit/UIKit.h> @class RootViewController; @interface AppController : NSObject <UIApplicationDelegate> { } +(NSString *)showAd:(NSString *)str title:(NSString *)tit; @property(nonatomic, readonly) RootViewController* viewController; @end
在.mm文件中定義如下
+(NSString *)showAd:(NSString *)str title:(NSString *)tit{ UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:tit message:str delegate:nil cancelButtonTitle:@"否" otherButtonTitles:@"是", nil]; [alertView show]; return @"hehe"; }
在js腳本中調用方式如下
if (cc.sys.isNative&&cc.sys.os==cc.sys.OS_IOS) { let ret = jsb.reflection.callStaticMethod("AppController","showAd:title:","title","message"); cc.log(ret)//打印輸出:hehe }
調用后oc代碼展示了彈框,並顯示了傳入參數
js代碼打印了調用返回值
oc調用js
在js中定義一個全局函數供oc調用
window.testMethod = (str)=>{ cc.log('window.testMethod' , str) return 'abcd' }
oc代碼調用方式如下
#include "cocos/scripting/js-bindings/jswrapper/SeApi.h" using namespace cocos2d; @implementation AppController @synthesize window; #pragma mark - #pragma mark Application lifecycle // cocos2d application instance static AppDelegate* s_sharedApplication = nullptr; +(NSString *)showAd:(NSString *)str title:(NSString *)tit{ UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:tit message:str delegate:nil cancelButtonTitle:@"否" otherButtonTitles:@"是", nil]; [alertView show]; // call the js function std::string strRet = "haha"; std::string jsCallStr = cocos2d::StringUtils::format("testMethod(\"%s\");", strRet.c_str()); se::Value *ret = new se::Value(); se::ScriptEngine::getInstance()->evalString(jsCallStr.c_str() , -1 , ret); NSLog(@"jsCallStr rtn = %s", ret->toString().c_str()); ////////////////// return @"hehe"; }
這里修改了showAd方法,增加call the js function相關部分
注意首先引入了SeApi.h文件,從而可以訪問命名空間se::
然后構建語句字符串,調用testMethod方法並傳入參數
再由ScriptEngine執行
可以看到js代碼打印了參數haha
oc代碼打印了返回值abcd
js調用java
場景中擺放一個label
點擊label調用java中的方法(傳入參數),並在label顯示該方法的返回結果(字符串)
js代碼如下
this.testlabel.node.on('touchend' , ()=>{ var rtn = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "show", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", "title", "message"); this.testlabel.string = rtn })
java代碼中,找到cocoscreator發布安卓工程所生成的AppActivity.java文件
並添加show方法如下
public static String show(String title, String message) { return title + "--" + message; }
以上運行時,點擊label后更新顯示了'title--message'
參考文獻
http://blog.csdn.net/hyczwl/article/details/51461797
http://blog.csdn.net/potato47/article/details/68954272