美文网首页
ios给RN发通知(react-native)

ios给RN发通知(react-native)

作者: SimpleTogether | 来源:发表于2017-12-07 11:26 被阅读417次

Constants.h文件

#import <Foundation/Foundation.h>
extern NSString * const NotifyName1;
@interface Constants : NSObject

@end

Constants.m文件

#import "Constants.h"
NSString * const NotifyName1 = @"NotifyName1";
@implementation Constants

@end

RNIOSExportJsToReact.h文件

#import <React/RCTEventEmitter.h>
@interface RNIOSExportJsToReact : RCTEventEmitter
+ (void)emitEventWithName:(NSString *)name andPayload:(NSDictionary *)payload;
@end

RNIOSExportJsToReact.m文件

#import "RNIOSExportJsToReact.h"
#import "Constants.h"
@implementation RNIOSExportJsToReact
RCT_EXPORT_MODULE();

- (NSArray<NSString *> *)supportedEvents {
  return @[NotifyName1]; //这里返回的将是你要发送的消息名的数组。
}
- (void)startObserving
{
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(emitEventInternal:)
                                               name:NotifyName1
                                             object:nil];
}
- (void)stopObserving
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)emitEventInternal:(NSNotification *)notification
{
  [self sendEventWithName:NotifyName1
                     body:notification.userInfo];
}

+ (void)emitEventWithName:(NSString *)name andPayload:(NSDictionary *)payload
{
  [[NSNotificationCenter defaultCenter] postNotificationName:name
                                                      object:self
                                                    userInfo:payload];
}
@end

native端调用:

[RNIOSExportJsToReact emitEventWithName:NotifyName1 andPayload:dict];

RN端调用:

componentDidMount(){
this.subScription = emitter.addListener('NotifyName1',(body) => {
      console.log(body)
    })
}

componentWillUnmount() {
    this.subScription.remove()
  }

相关文章

网友评论

      本文标题:ios给RN发通知(react-native)

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