RN - iOS原生发送通知给RN

1.原生创建一个CEPushManager类继承于RCTEventEmitter


CEPushManager.h


CEPushManager.m


2.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  =====================

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容