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
Once your native module has been registered and conformed, you may use any method available in the EventEmitter class. To receive events, you can just use the addListener method from EventEmitter. To send events, you can just use the emit method from EventEmitter.
It is an intuitive language for iOS, macOS, tvOS, watchOS, and more. Swift as cross-platform development is the process of creating an application that may run on multiple platforms. This may be achieved with tools like React Native, Xamarin, and Flutter. Apps may be deployed on both on Android system and iOS.
In most cases, React Native will use JavaScriptCore, the JavaScript engine that powers Safari. Note that on iOS, JavaScriptCore does not use JIT due to the absence of writable executable memory in iOS apps.
In order to access your native module from JavaScript you need to first import NativeModules from React Native: import { NativeModules } from 'react-native'; You can then access the CalendarModule native module off of NativeModules .
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With