1、Android 如何接收URL参数
在文件android/app/src/main/java/.../MainActivity.java 重写方法 onNewIntent,代码如下
public class MainActivity extends ReactActivity {
...
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
String action = intent.getAction();
Uri data = intent.getData(); // 获取URL上的所有数据
if (data != null) {
WritableMap params = Arguments.createMap();
params.putString("url_query", data.getQuery()); // 获取URL上的参数
params.putString("url_scheme", data.getScheme()); // 获取scheme
params.putString("url_host", data.getHost()); // 获取host sendEvent(Objects.requireNonNull(getReactNativeHost().getReactInstanceManager().getCurrentReactContext()), "XXX", params); // ‘xxx'这个可以自己随便定义,react native监听的名字,建议跟ios保持一致
}
}
private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
}
...
}
2、IOS 如何接收URL参数
2.1 在ios/文件夹下新建文件 XXX.m ,最好在xcode下新建, 此处的XXX建议与上面Android的'xxx'保持一致, 以下所有XXX均表示同一意思,建议使用同一个名称。
@implementation XXX
RCT_EXPORT_MODULE();
- (NSArray<NSString *> *)supportedEvents
{
return @[@"XXX"];
}
- (instancetype)init {
if (self = [super init]) {
//初始化的时候注册事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fireData:) name:@"fireData" object:nil];
}
return self;
}
+ (BOOL)requiresMainQueueSetup{
return YES;
}
+ (id)allocWithZone:(NSZone *)zone {
static XXX *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [super allocWithZone:zone];
});
return sharedInstance;
}
- (void)fireData:(NSMutableDictionary *)callbackMap{
// 给React Native发送数据,RN监听XXX,建议与Android名称保持一致
[self sendEventWithName:@"XXX" body:callbackMap];
}
2.2 在ios/文件夹下新建文件 XXX.h
#ifndef XXX_h
#define XXX_h
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
@interface XXX : RCTEventEmitter <RCTBridgeModule>
- (void)fireData:(NSMutableDictionary *)notification;
@end
#endif
2.3 更新 ios/projectName/AppDelegate.m
...
#import "XXX.h" // 引入2.2的文件
...
...
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
NSMutableDictionary * callbackMap = [NSMutableDictionary dictionary];
[callbackMap setObject:url.query forKey:@"url_query"];
[callbackMap setObject:url.scheme forKey:@"url_scheme"];
[callbackMap setObject:url.host forKey:@"url_host"];
XXX * xxx = [XXX allocWithZone:nil]; // xxx随意起参数名
[xxx fireData:(callbackMap)]; // xxx是上一行的参数名
return [RCTLinkingManager application:application openURL:url options:options];
}
...
// 注意:一定要在这个@end之前写上面的代码,可以紧挨着,但一定要在它的前面
@end
3、React Native接收数据 (我是在App.tsx里监听的)
import { NativeEventEmitter, NativeModules } from 'react-native';
...
const XXX = new NativeEventEmitter(NativeModules.XXX);
XXX.addListener('XXX', async (callBackMap: any) => {
// 处理接收到的数据
...
}