将事件发送到JS React Native

时间:2019-05-02 12:29:00

标签: objective-c react-native

我在Objective C事件发射器上实现了React Native,在这里我创建了一个发射器类,该类将事件发送给React Native,并且似乎可以正常工作:

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

@interface PlayerEventsEmitter : RCTEventEmitter <RCTBridgeModule>

@end


#import "PlayerEventsEmitter.h"

@implementation PlayerEventsEmitter
{
   bool hasListeners;
}

RCT_EXPORT_MODULE();

+ (id)allocWithZone:(NSZone *)zone {
   static PlayerEventsEmitter *sharedInstance = nil;
   static dispatch_once_t onceToken;
   dispatch_once(&onceToken, ^{
       sharedInstance = [super allocWithZone:zone];
   });
return sharedInstance;
}


- (NSArray<NSString *> *)supportedEvents {
    return @[@"onMediaLoaded", @"onPlaying", @"onPause", @"onError", @"onEnded", @"onBuffering", @"onTimeUpdate", @"onStateUpdate"];
}

- (void)startObserving {
    hasListeners = YES;
}

- (void)stopObserving {
    hasListeners = NO;
}

- (void)sendEventName:(NSString *)eventName body:(id)body {
   if (hasListeners) {
      [self sendEventWithName:eventName body:body];
}
}

@end

但是在JS上,当我这样做时:

import {NativeEventEmitter, NativeModules} from 'react-native';
import isFunction from 'lodash/isFunction';
import noop from 'lodash/noop';
import createMiddleware from './middleware';

const nativeAdapter = NativeModules.RNNativePlayerAdapter; //  eslint-disable-line
const { ModuleWithEmitter } = NativeModules;
const eventEmitter = new NativeEventEmitter(ModuleWithEmitter);

const onMediaLoaded = (event) => {
  console.log(event);
}

const onPlaying = (event) => {
  console.log(event);
}

const subscription1 = eventEmitter.addListener('onMediaLoaded', onMediaLoaded);
const subscription2 = eventEmitter.addListener('onPlaying', onPlaying);

export default class NativeAdapter {
  constructor() {
    console.log('nativeAdapter: ', nativeAdapter);
    console.log('NativeModules: ', NativeModules);

     this.subscription = eventEmitter.addListener(
       'onMediaLoaded',
         (onMediaLoaded) => {
             console.log('onMediaLoaded');
        }
      );
    }
}

我得到一个错误: “本机模块不能为空”

我完全按照文档进行操作: https://facebook.github.io/react-native/docs/native-modules-ios

请帮助。

谢谢, 克劳迪(Claudiu)

1 个答案:

答案 0 :(得分:0)

该错误表示您尚未链接模块。模块基本上是库,因此您必须将它们链接到主项目。检查一下:

https://facebook.github.io/react-native/docs/linking-libraries-ios