React Native Sending Events to JavaScript in Swift

2020-05-28 10:58发布

问题:

How can I send event's to JavaScript in Swift?

There is examples of Objc code how to send event to JavaScript, but I need to do in swift?

#import "RCTBridge.h"
#import "RCTEventDispatcher.h"

@implementation CalendarManager

@synthesize bridge = _bridge;

- (void)calendarEventReminderReceived:(NSNotification *)notification
{
  NSString *eventName = notification.userInfo[@"name"];
  [self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder"
                                               body:@{@"name": eventName}];
}

@end

回答1:

I was just trying to figure this out myself. It was actually surprisingly easy. Heres how I did it:

EventTests.m

#import "RCTBridgeModule.h"

@interface RCT_EXTERN_MODULE(EventTests, NSObject)

RCT_EXTERN_METHOD( testEvent:(NSString *)eventName )

@end

EventTests.Swift

import UIKit

@objc( EventTests )
class EventTests: NSObject {
    // Swift doesn't have synthesize - just define the variable
    var bridge: RCTBridge!

    @objc func testEvent( eventName: String ) {
        self.bridge.eventDispatcher.sendAppEventWithName( eventName, body: "Woot!" )
    }
}

MyModule.js

var React      = require( 'react-native' );
var EventTests = require( 'NativeModules' ).EventTests;

var {
    Component,
    NativeAppEventEmitter
} = React;

var testEventName = 'test';

class MyModule extends Component {

    constructor( options ) {
        super( options );

        // Register for our test event
        NativeAppEventEmitter.addListener( testEventName, ( body ) => {
            console.log( body );
        });

        // Call objective c function, which will emit our test event
        EventTests.testEvent( testEventName );
    }
}

module.exports = MyModule;

Also make sure to include a few imports in your bridging header:

#import "RCTBridge.h"
#import "RCTEventDispatcher.h"