ios 原生通知 ReactNative


本地模块也可以给JavaScript发送事件通知。最直接的方式是使用eventDispatcher:
- (void)calendarEventReminderReceived:(NSNotification *)notification
{
//  NSString *eventName = notification.userInfo[@"name"];
   NSString *eventName = @"123";

  [self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder"
                                               body:@{@"name": eventName}];
}

在JavaScript中可以这样订阅事件:

var subscription = DeviceEventEmitter.addListener(
  'EventReminder',
  (reminder) => {
    alert(reminder.name);
    // console.log(reminder.name)
  }
);

ios原生 源码

.h

#import <Foundation/Foundation.h>
#import "RCTBridgeModule.h"


@interface CalendarManager : NSObject<RCTBridgeModule>

@end

.m

#import "CalendarManager.h"
#import "RCTBridge.h"
#import "RCTEventDispatcher.h"

@interface CalendarManager ()

//@property (nonatomic,strong)bridge;
@end

@implementation CalendarManager

@synthesize bridge = _bridge;


RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(notification){
  
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"EventReminder" object:nil userInfo:nil];
  [self calendarEventReminderReceived:nil];
}


- (void)calendarEventReminderReceived:(NSNotification *)notification
{
//  NSString *eventName = notification.userInfo[@"name"];
   NSString *eventName = @"123";

  [self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder"
                                               body:@{@"name": eventName}];
}


@end

js 调用代码

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */



import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TouchableOpacity,
  NativeAppEventEmitter,
  DeviceEventEmitter,
  View
} from 'react-native';

import CalendarManagerModel  from './CalendarManagerModel';


var subscription = DeviceEventEmitter.addListener(
  'EventReminder',
  (reminder) => {
    alert(reminder.name);
    // console.log(reminder.name)
  }
);

class RNProject extends Component {
  render() {
    return (
      <View style={styles.container}>
          <TouchableOpacity onPress={()=>{
            CalendarManagerModel.notification();
          }} >
            <Text style={styles.emptyTxt}>{
              '点击'
            }</Text>
       </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('RNProject', () => RNProject);

 

 

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注