最近项目需要做分享模块,用的ShareSDK,但是官方没有对应的React Native 的SDK,没办法,只好下载对应的原生SDK,然后封装后暴露给React Native调用,在此简单记录下流程。
1.新建一个类,这个类就是要暴露给React Native使用的。
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
NS_ASSUME_NONNULL_BEGIN
//需要遵循RCTBridgeModule协议
@interface ShareManager : NSObject<RCTBridgeModule>
@end
NS_ASSUME_NONNULL_END
2.类的实现文件如下
#import "ShareManager.h"
#import <ShareSDK/ShareSDK.h>
@implementation ShareManager
//指定React Native中的模块名,如果不指定,默认是类名
RCT_EXPORT_MODULE();
//指定暴露给React Native的模块API
//RCTResponseSenderBlock参数为回调,指明方法调用完成后回传给js的值
RCT_EXPORT_METHOD(shareWith:(NSString *)platform text:(NSString *)text url:(NSString *)url title:(NSString *)title callback:(RCTResponseSenderBlock)callback)
{
}
- 具体实现如下
@implementation ShareManager
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(shareWith:(NSString *)platform text:(NSString *)text url:(NSString *)url title:(NSString *)title callback:(RCTResponseSenderBlock)callback)
{
NSMutableDictionary * params = [NSMutableDictionary dictionary];
NSUInteger type = SSDKPlatformTypeFacebook;
if ([platform isEqualToString:@"Facebook"]) {
type = SSDKPlatformTypeFacebook;
[params SSDKSetupShareParamsByText:text images:@"https://fg.glf.com.cn/sice_app_icon_1024.png" url:[NSURL URLWithString:url] title:title type:SSDKContentTypeWebPage];
} else {
type = SSDKPlatformTypeLine;
[params SSDKSetupLineParamsByText:text image:@"https://fg.glf.com.cn/sice_app_icon_1024.png" type:SSDKContentTypeText];
}
[ShareSDK share:type parameters:params onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
//分享完成后,把分享结果回传给js端
callback(@[[NSNumber numberWithInteger:state]]);
}];
}
@end
RCTResponseSenderBlock的官方定义如下,回传给js的值必须放在数组中
/**
* The type of a block that is capable of sending a response to a bridged
* operation. Use this for returning callback methods to JS.
*/
typedef void (^RCTResponseSenderBlock)(NSArray *response);
4.React Native中新建一个Share类,定义对应的方法,调用原生模块暴露的方法。
class Share {
static shareTo(type, text = '', url, title = '') {
if (IS_IOS) {
//这里是导出原生模块,"ShareManager"即是我们的原生模块名称
const shareManager = NativeModules.ShareManager;
//js中调用原生方法时,方法名只会取原生的第一个字段。
shareManager.shareWith(type, text, url, title, (res) => {
console.log(res);
});
} else {
}
}
}
export default Share;
5.部分数据类型从原生到js可能需要转换,具体可参考官方文档
https://reactnative.cn/docs/native-modules-ios
网友评论