Home > Blockchain >  Listening to Swift events in Javascript; React Native Native Modules
Listening to Swift events in Javascript; React Native Native Modules

Time:09-06

I am trying to figure out how my Javascript code can listen to my native modules events that are being emitted from my Swift code in my React Native app. I cannot seem to find any official documentation and anything I find after a Google search is either outdated or is written in Obj-C whereas my event is fired from my Swift code. I hope that makes sense and any help would be appreciated!

Thanks, Aiden

CodePudding user response:

It's actually described in quite a detail here.

  1. First you create an Objective-C bridge to catch events from Swift.
  2. Then in Objective-C again, you implement an RCTEventEmitter (can be same or different class) This is the class that will send events to JS. The events are sent using sendEventWithName function

Here's a very rough sketch:

Step 1: catch Swift events

@interface MyBridge() <SomeDelegate>

@end

@implementation MyBridge

// Here's my delegate function:
- (void)myDelegateCalled 
     // Received an event
     // Calling bridge to send the event to JS
     BridgeEventEmitter send:someData
     ...

Step 2: send them to JS

// Here's the BridgeEventEmitter:
@interface BridgeEventEmitter : RCTEventEmitter <RCTBridgeModule>
@end

@implementation BridgeEventEmitter
  (void)send:(NSString *)something
{
  [self sendEventWithName:@"EventName" body:something];
}

CodePudding user response:

I don't think you can emit an event in custom swift code and then catch it in your react native code. I might be wrong. maybe consider local storage or server-side storage?

  • Related