点击上方<font color=blue>亿元程序员</font>+关注和<font color=orange>★</font>星标
引言
Cocos如何跟iOS通信
大家好,相信小伙伴们通过阅读笔者前几期的文章《你那么牛,怎么不教我打iOS包?安排!》,对Cocos如何打iOS包有了一定的了解。
但是,除了把iOS包打出来,另外还有一个重要的就是要能够调用iOS提供的OC方法以及监听OC发送的事件。
本文重点介绍一下Cocos如何跟iOS通信,如果对您或者其他人有帮助,建议转发、收藏、点赞和在看!
1.为什么要跟iOS通信?
通常我们将游戏打成iOS包之后,我们还需要接入登陆、支付或者广告等功能,通常这些平台会提供接口给到iOS原生。
因此我们想要接入这些接口,必须要使用原生OC(Objective-C 全文简称OC)去接入,接入完成后,由于游戏开发和原生的语言不同,我们还需要实现Cocos与iOS的通信。
那Cocos如何实现与iOS的通信呢?
2.Cocos与iOS的通信
Cocos想要与iOS进行通信,通常有以下两种方法:
1.基于反射机制实现 JavaScript 与 iOS 系统原生通信
在 Cocos Creator 中提供了依靠语言反射机制的跨语言通信方式,使JavaScript 可以直接调用 OC 函数的方法。
Cocos调用iOS方法的形式如下:
var result = native.reflection.callStaticMethod(className, methodName, arg1, arg2, .....);
完整示例:
if(sys.isNative && (sys.os == sys.OS.IOS || sys.os == sys.OS.OSX)){
var ret = native.reflection.callStaticMethod("NativeOcClass",
"callNativeUIWithTitle:andContent:",
"cocos2d-js",
"Yes! you call a Native UI from Reflection");
}
iOS调用Cocos方法如下:
#include "application/ApplicationManager.h"
#include "cocos/bindings/jswrapper/SeApi.h"
CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread([=](){
se::ScriptEngine::getInstance()->evalString(script.c_str());
});
注意:由于苹果对于反射机制相关的API的审核比较严格,主要防止热更代码,有拒审风险,所以该方法不是很建议使用。
2.使用 JsbBridge 实现 JavaScript 与 OC 通信
由于通过反射机制实现通信的方法比较复杂,Cocos为我们准备了JsbBridge的方法,可以理解成Cocos与iOS通信的桥梁。
在Cocos这边,在脚本层提供了 sendToNative
和 onNative
两个接口,定义如下:
分别是给发送信息到iOS和监听iOS的事件。
// JavaScript
export namespace bridge{
/**
* Send to native with at least one argument.
*/
export function sendToNative(arg0: string, arg1?: string): void;
/**
* Save your own callback controller with a JavaScript function,
* Use 'jsb.bridge.onNative = (arg0: String, arg1: String | null)=>{...}'
* @param args : received from native
*/
export function onNative(arg0: string, arg1?: string | null): void;
}
同样的,在iOS这边,也有两对应的接口, sendToScript
和 callByScript
,定义如下:
//Objective-c
typedef void (^ICallback)(NSString*, NSString*);
@interface JsbBridge : NSObject
+(instancetype)sharedInstance;
-(bool)setCallback:(ICallback)cb;
-(bool)callByScript:(NSString*)arg0 arg1:(NSString*)arg1;
-(void)sendToScript:(NSString*)arg0 arg1:(NSString*)arg1;
-(void)sendToScript:(NSString*)arg0;
@end
其中 sendToScript
用于调用脚本层代码,而 callByScript
用于响应脚本层的调用。
我们需要实现 ICallback
接口,并且使用 setCallback
注册,来响应 callByScript
的具体行为。
3.Cocos与iOS的通信实例
1.资源准备
首先用CocosCreator3.8.3创建一个项目,然后在界面中简单添加1个背景以及2个按钮,分别用来测试调用iOS方法和监听iOS事件。
2.写代码
首先添加一个Main.ts
脚本,然后分别监听两个按钮的点击事件。
上面关键的2
个方法如下:
- 调用我们在
OC
写好的showAlert
方法,传递的参数是一句话,这个方法是调用系统的提示框。
native.bridge.sendToNative('showAlert', "Cocos调用了iOS的系统提示框");
- 通过
native.bridge.onNative
监听OC的事件,然后在OC
写好的testiOSEvent
方法进行测试监听是否成功。
native.bridge.onNative = (arg0: string, arg1: string): void => {
if (arg0 == 'ok') {
native.bridge.sendToNative('showAlert', "成功接收到iOS的事件");
}
return;
}
native.bridge.sendToNative('testiOSEvent');
3.导出XCode工程
由于在前面的文章有比较详细的介绍,我们这里就不再重复描述。通过构建发布工具发布即可。
4.通过XCode打开工程
找到我们的工程目录,在项目的build->iOS->proj
,然后用XCode
进行打开。
5.编写OC方法
找到AppDelegate.m
,在didFinishLaunchingWithOptions
方法中添加我们的测试代码。
上面2
个关键的方法如下:
- 通过
setCallback
监听我们在Cocos发送的事件。通过第一个参数arg0
来判断事件。
static ICallback cb = ^void (NSString* _arg0, NSString* _arg1){
if([_arg0 isEqual:@"showAlert"]){
// 创建 UIAlertController 实例
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"
message:_arg1
preferredStyle:UIAlertControllerStyleAlert];
// 添加一个确定按钮
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定"
style:UIAlertActionStyleDefault
handler:nil];
[alertController addAction:okAction];
// 获取当前的根视图控制器
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
// 显示提示框
dispatch_async(dispatch_get_main_queue(), ^{
[rootViewController presentViewController:alertController animated:YES completion:nil];
});
}
else if([_arg0 isEqual:@"testiOSEvent"])
{
JsbBridge* m = [JsbBridge sharedInstance];
[m sendToScript:@"ok"];
}
};
JsbBridge* m = [JsbBridge sharedInstance];
[m setCallback:cb];
- 当接收到
showAlert
事件时,我们调用系统的提示框。
if([_arg0 isEqual:@"showAlert"]){
// 创建 UIAlertController 实例
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"
message:_arg1
preferredStyle:UIAlertControllerStyleAlert];
// 添加一个确定按钮
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定"
style:UIAlertActionStyleDefault
handler:nil];
[alertController addAction:okAction];
// 获取当前的根视图控制器
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
// 显示提示框
dispatch_async(dispatch_get_main_queue(), ^{
[rootViewController presentViewController:alertController animated:YES completion:nil];
});
}
- 当接收到
testiOSEvent
事件时,我们通过方法sendToScript
进行回复。
if([_arg0 isEqual:@"testiOSEvent"])
{
JsbBridge* m = [JsbBridge sharedInstance];
[m sendToScript:@"ok"];
}
6 .效果演示
点击调用OC方法按钮成功弹出系统提示。
点击调用监听OC事件按钮成功接收到OC的事件,然后调用系统提示。
结语
今天的分享到这里,如果对您或者其他人有帮助,建议转发、收藏、点赞和在看!
更多实用源码可通过阅读原文搜索"亿元程序员"获取。
我是"亿元程序员",一位有着8年游戏行业经验的主程。在游戏开发中,希望能给到您帮助, 也希望通过您能帮助到大家。
AD:笔者线上的小游戏《填色之旅》《方块掌机经典》《贪吃蛇掌机经典》《重力迷宫球》大家可以自行点击搜索体验。
实不相瞒,想要个赞和在看!请把该文章分享给你觉得有需要的其他小伙伴。谢谢!
推荐专栏:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。