美文网首页
ios原生通知RN一套

ios原生通知RN一套

作者: 慧惠 | 来源:发表于2019-06-26 19:29 被阅读0次

ios原生写法:

#import "RCTEventEmitter.h"

@interface RNNotification : RCTEventEmitter<RCTBridgeModule>

- (void)sendRNNotification:(NSNotification *)notification;
+ (id)allocWithZone:(NSZone *)zone ;

@end

#import "RNNotification.h"

@implementation RNNotification

RCT_EXPORT_MODULE();

-(NSArray*)supportedEvents {
  
  return@[key1,key2,key3];//定义RN能够接收的通知key

}

+ (id)allocWithZone:(NSZone *)zone {
  static RNNotification *instance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    instance = [super allocWithZone:zone];
    [[NSNotificationCenter defaultCenter] addObserver:instance selector:@selector(sendRNNotification:) name:SENDRNNOTIFICATION object:nil];
  });
  return instance;
}


- (void)sendRNNotification:(NSNotification *)notification
{
  if (self.bridge == nil) {
    return;
  }
  NSDictionary *object = [NSDictionary dictionaryWithDictionary:notification.object];
  NSString *notifyName = [object objectForKey:@"name"];
  [self sendEventWithName:notifyName
                     body:@{
                            @"value":[object objectForKey:@"value"]
                            }];
}

-(void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

特别注意单例的方法+ (id)allocWithZone:(NSZone )zone *
之前自定义了+shareInstanse,里面实现一样,但是会有bug:
bridge is not set.**。
还要注意的一点是,+load在RCT_EXPORT_MODULE()存在的情况下是不能自定义的,因为RCT_EXPORT_MODULE()的内部已经实现过+load方法了。

在继承RCTEventEmitter的前提下,supportedEvents和RCT_EXPORT_MODULE()都是必须要写上去的。

RN里面的写法是:

//创建nativeNoticeBridge
import {NativeModules,NativeEventEmitter} from "react-native";
var nativeNoticeBridge = NativeModules.RNNotification;//你的类名
const NativeNoticeCenter = new NativeEventEmitter(nativeNoticeBridge);

//调用
_xx=()=>{
this.listener = NativeNoticeCenter.addListener('通知名',(notify)=>this._notify(notify));
}

_notify =(notify)=>{

}

Rn的调用没有什么要特别注意的,创建Bridge,然后调用就完事

相关文章

网友评论

      本文标题:ios原生通知RN一套

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