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?
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"
It is insane. How to pass anything as an event to Javascript, if this event is generated by Swift?
I am stuck with the same issue here: "Subclass RCTEventEmitter instead" The following does not work anymore.
self.bridge.eventDispatcher.sendAppEventWithName( eventName, body: "Woot!" )
I tried:
var emitter: RCTEventEmitter = RCTEventEmitter()
Instead of:
var bridge: RCTBridge!
Conesquently:
self.emitter.sendEvent(withName: eventName, body: "Woot!")
Instead of
self.bridge.eventDispatcher.sendAppEventWithName( eventName, body: "Woot!" )
From bad to worst, I go from a warning to the following hard error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error when sending event: Location with body: woot. Bridge is not set. This is probably because you've explicitly synthesized the bridge in RCTEventEmitter, even though it's inherited from RCTEventEmitter.'
The documentation is very poor and old. It looks that not many people is using this hot garbage. Very frustrating.
This is an old implementation and it no longer works:
enter link description here
Another article, not very useful:
enter link description here
Very thorough and complex implementation, no one knows if it still works. In my case it doesn't, I get the same error above:
enter link description here
Then there are several objective-c swift cocktails, which I cannot drink at my age:
enter link description here