1.原生创建一个CEPushManager类继承于RCTEventEmitter
CEPushManager.h CEPushManager.m2.RN代码中:
import {
NativeEventEmitter,
NativeModules
} from 'react-native';
const { CEPushManager } = NativeModules;
const MyPushManager = (Platform.OS.toLowerCase() != 'ios')?'':new NativeEventEmitter(CEPushManager);
//监听
this.subscription = (Platform.OS.toLowerCase() != 'ios')?'':MyPushManager.addListener('onNotification',(reminder) => {
// alert(`yp测试_推送 RN收到OC发来---->${objectConvertToJsonString(reminder)}`)
/* 处理OC发来的通知消息 */
});
componentWillUnmount() {
if (Platform.OS.toLowerCase() === 'ios') {
//移除监听
this.subscription.remove();
}
}
3.在原生中需要的地方发送通知
[[NSNotificationCenter defaultCenter] postNotificationName:NATIVE_ONNOFIFICATION object:nil userInfo:@{@"key": @"value"}];
//========================= OC代码复制 start =====================
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
#import <React/RCTBridge.h>
NS_ASSUME_NONNULL_BEGIN
@interface CEPushManager : RCTEventEmitter <RCTBridgeModule>
@end
NS_ASSUME_NONNULL_END
#import "CEPushManager.h"
#define NATIVE_TO_RN_ONNOFIFICATION @"onNotification"
#define NATIVE_ONNOFIFICATION @"native_onNotification"
@implementation CEPushManager
RCT_EXPORT_MODULE()
-(NSArray*)supportedEvents {
return@[NATIVE_TO_RN_ONNOFIFICATION];
}
- (void)nativeSendNotificationToRN:(NSNotification*)notification {
NSLog(@"NativeToRN notification.userInfo = %@", notification.userInfo);
dispatch_async(dispatch_get_main_queue(), ^{
[self sendEventWithName:NATIVE_TO_RN_ONNOFIFICATION body:notification.userInfo];
});
}
- (void)startObserving {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(nativeSendNotificationToRN:)
name:NATIVE_ONNOFIFICATION
object:nil];
}
- (void)stopObserving {
[[NSNotificationCenter defaultCenter]removeObserver:self name:NATIVE_ONNOFIFICATION object:nil];
}
@end
//========================= OC代码复制 end =====================
网友评论