iOS原生OC向React Native發送消息、事件、通知

 

RCTEventEmitter

 

此篇僅獻給剛剛入門的同志們。html

你們在使用React Native的時候,都會比較關心原生和React Native的交互問題。React Native給原生髮送消息,在中文官網上講得也比較明白,按照上面的例子,相信你們均可以實現出來。
可是在原生給React Native發送消息的時候,你會發現試了不少次,可能就是不成功,想一想也是不知道爲啥,對於剛剛上路的小夥伴來講,這真的是讓人很是煩惱,不要着急,若是你看到了這篇文章,恭喜你,能夠好好去喝一杯咖啡了。
官方文檔介紹,iOS端繼承RCTEventEmitter類,使用sendEventWithName方法。react

- (void)sendEventWithName:(NSString *)name body:(id)body;

 

在網上搜了不少資料,發現介紹的都是0.28之前的方法RCTDeviceEventEmitter,可是如今這個方法廢棄了,不建議使用了。ios

/**
 * Deprecated, do not use.
 */
- (void)sendDeviceEventWithName:(NSString *)name body:(id)body
__deprecated_msg("Subclass RCTEventEmitter instead");

 

不知道你們在使用RCTEventEmitter類中這個方法sendEventWithName的時候,有沒有碰到以下問題:
RCTEventEmitter裏邊這個對象_bridge爲空。死活就是崩了。react-native

*** Assertion failure in -[RCTEventEmitter sendEventWithName:body:]()

Bridge is not set. This is probably because you've explicitly synthesized the bridge in WSNotification, even though it's inherited from RCTEventEmitter

 

以下代碼所示,若是是經過[WSNotification alloc] init]; 來初始化,而後調用OCsendMessageToReactNative 方法,就會報_bridge爲空的異常。
經過添加自定義支持的方法名(在-(NSArray<NSString *> *)supportedEvents {} 中設置)。該方法在React Native中存在對應的監聽事件(.addListener('OCSendToRN',(reminder) =>);)時就會調用。經過supportedEvents {} 方法中打印,咱們知道,該WSNotification類在這個回調中已經初始化好了,而咱們在須要的地方還經過[WSNotification alloc] init]; 這樣的方式初始化,就會是另外一個新的對象了,和原有的WSNotification (RCTEventEmitter)已經不是一個東東了。post

由此可知,RCTEventEmitter對象,不須要咱們來初始化。直接調用便可。spa

// WSNotification.h 
#import <React/RCTEventEmitter.h>
#import <React/RCTBridgeModule.h>

@interface WSNotification : RCTEventEmitter <RCTBridgeModule>

-(void)OCsendMessageToReactNative:(NSDictionary *)dictionary;

@end
-----------------------------------------
// WSNotification.m
#import "WSNotification.h"

@interface WSNotification()
@end

@implementation WSNotification

RCT_EXPORT_MODULE();

- (NSDictionary<NSString *, NSString *> *)constantsToExport {
  return @{@"name": @"OCSendToRN"};
}

-(NSArray<NSString *> *)supportedEvents {
  NSLog(@"----------->supportedEvents--->%@  self-->%@",self.bridge, self);
  return@[@"OCSendToRN"];
}

-(void)startObserving {
  NSLog(@"startObserving------>%@  self--->%@",self.bridge,self);
}

-(void)stopObserving {
  
}

-(void)OCsendMessageToReactNative:(NSDictionary *)dictionary {
  NSLog(@"OCsendMessageToReactNative------>%@  self--->%@",self.bridge, self);
  [self sendEventWithName:@"OCSendToRN" body:dictionary];
  NSLog(@"oc發送RN----->OCSendToRN");
}
@end

 

敲黑板-----------------------

如何避免不從新建立WSNotification,而不影響使用[self sendEventWithName:@"OCSendToRN" body:dictionary];code

使用通知component

在-(void)startObserving;開啓通知
在-(void)stopObserving;移除通知server

//  WSNotification.h
#import <React/RCTEventEmitter.h>
#import <React/RCTBridgeModule.h>

@interface WSNotification : RCTEventEmitter <RCTBridgeModule>

+(void)OCsendMessageToReactNative:(NSDictionary *)dictionary;

@end

-------------------------------
#import "WSNotification.h"

@interface WSNotification()

@end

@implementation WSNotification

RCT_EXPORT_MODULE();


- (NSDictionary<NSString *, NSString *> *)constantsToExport {
  return @{@"name": @"OCSendToRN",@"ocName":@"OC直接定義的常量"};
}

-(NSArray<NSString *> *)supportedEvents {
  NSLog(@"----------->supportedEvents--->%@  self-->%@",self.bridge, self);
  return@[@"OCSendToRN"];
}

-(void)startObserving {
  NSLog(@"startObserving------>%@  self--->%@",self.bridge,self);
  
  for (NSString *notifiName in [self supportedEvents]) {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(OCsendToReactNative:) name:notifiName object:nil];
  }

}

-(void)stopObserving {
  // 在此移除通知
  [[NSNotificationCenter defaultCenter] removeObserver:self name:@"OCSendToRN" object:nil];
  NSLog(@"oc----->在此移除通知");
}

+(void)OCsendMessageToReactNative:(NSDictionary *)dictionary {
  [[NSNotificationCenter defaultCenter] postNotificationName:@"OCSendToRN" object:nil userInfo:dictionary];
}

-(void)OCsendToReactNative:(NSNotification *)notification {
  NSLog(@"OCsendToReactNative------>%@  self--->%@",self.bridge, self);
  [self sendEventWithName:@"OCSendToRN" body:notification.userInfo];
  NSLog(@"oc發送RN----->%@",notification.userInfo[@"name"]);
}

@end

 

對應的React Nativehtm

//引入文件
import {NativeModules, NativeEventEmitter} from 'react-native';


const { WSNotification } = NativeModules;
console.log('接收OC定義的常量--->'+WSNotification.name+' -------->'+WSNotification.ocName);
const calendarManagerEmitter = new NativeEventEmitter(WSNotification);

const subscription = calendarManagerEmitter.addListener('OCSendToRN',(reminder) => console.log('RN收到OC發來---->'+reminder.name),

// 經過OC中constantsToExport 傳過來的參數,動態設置監聽的方法        
//        const subscription = calendarManagerEmitter.addListener(WSNotification.name,(reminder) => console.log('RN收到OC發來---->'+reminder.name);

// 別忘了取消訂閱,一般在componentWillUnmount生命週期方法中實現。
// subscription.remove();

 

React Native還提供了,由原生直接設置變量給React Native,在初始化的時候,就已經設置好了,不支持後期動態更改。使用以下方法,便可直接轉參到React Native。

- (NSDictionary<NSString *, NSString *> *)constantsToExport;
相關文章
相關標籤/搜索