美文网首页ReactNative
RN - iOS原生发送通知给RN

RN - iOS原生发送通知给RN

作者: iOS_杨平 | 来源:发表于2019-02-28 15:52 被阅读0次

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

    相关文章

      网友评论

        本文标题:RN - iOS原生发送通知给RN

        本文链接:https://www.haomeiwen.com/subject/bjrccqtx.html