React native rcteventemitter (OC method calls RN method)

React native rcteventemitter (OC method calls RN method)

You need to send a notification from iOS to RN, and RCTEventEmitter will be used

I post the code directly:

//.h
+ (void)postNotiToReactNative:(NSString *)type args:(id)args;
//.m
RCT_EXPORT_MODULE();

- (NSArray<NSString *> *)supportedEvents {
    return @[@"SpotifyHelper"]; //Here you will return an array of message names that you want to send.
}
- (void)startObserving
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(emitEventInternal:)
                                                 name:@"event-emitted"
                                               object:nil];
}
- (void)stopObserving
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)emitEventInternal:(NSNotification *)notification
{
    [self sendEventWithName:@"SpotifyHelper"
                       body:notification.object];
}

+ (void)postNotiToReactNative:(NSString *)type args:(id)args{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"type"] = type;
    dic[@"args"] = args;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"event-emitted" object:dic];
}

Be careful

Once RCT ﹣ export ﹣ module(); declares that the class is export ﹣ module, then the instance of the class has been created. If you create an instance of the class (alloc or new) elsewhere, RN will not recognize the instance of the class correctly

Corresponding RN Code:

'use strict';

import React,{Component} from 'react';
import {
  ·
  ·
  ·
  NativeModules,
  NativeEventEmitter,
} from 'react-native';

import Main from './app/HJMain';

var nativeBridge = NativeModules.RNIOSExportJsToReact;//Your class name
const NativeModule = new NativeEventEmitter(nativeBridge);

export default class Haojia extends React.Component {

  render() {
    return (
        <Main />
    );
  }

  componentDidMount(){
    this.subscription = NativeModule.addListener('SpotifyHelper',(data)=>this._getNotice(data));
  }

  _getNotice (body) {//body see what you pass
      //A series of operations
  }

  componentWillUnmount() {
    //Delete listening
    this.subscription.remove()
  }

}

Add rniosexportjstoreact (parameter) where OC needs to call the RN method

The above is the code of OC calling RN method. Over!

Tags: React iOS

Posted on Thu, 30 Apr 2020 21:52:31 -0700 by seansd