You are building a React Native app and want to work in Swift as much as possible while minimizing Objective-C. This task can be a real challenge. Since the Objective-C runtime is leveraged for communicating with the JavaScript context and Swift does not support macros it will be necessary to use Objective-C to bridge React Native and Swift.
Read Exporting Swift
to get an understanding of how it can be done. First you need an Objective-C implementation file.
In this case it is called ReactNativeEventEmitter.m
and it has what you need to make a module and
method available to React Native. In ReactNativeEventEmitter.swift
you will find the actual implementation
with the class and function marked with objc
so both are available to the Objective-C runtime.
When your app starts up the module and function will be made available to React Native which will create
and instance of the module which is ReactNativeEventEmitter
and sets the critical bridge property which
allows for communicating between Swift and React Native.
Once React Native initializes ReactNativeEventEmitter
it will be registered with EventEmitter
so
it can be used to send events. Be sure to put all of your events into the array of events returned by
supportedEvents
as it is used to check for valid events on the React Native side. Events which are
not recognized will cause an error.
Brennan Stehling - 2017
thanks for the easy, great code snippet!
just for future reference, especially for those who are developing RN library / package, in which you have separate project with the application, and you are "injecting" your library to the application by doing
yarn add files://...
for testing purpose, in order to test thenew NativeModule()
properly, you will need to publish the library / package first andyarn
it into the applicationI was facing the issue (for 3 days 😢 ) where the iOS part has already sent the event properly, no error message whatsoever, but the event is not received in the Javascript side. Only after I remember that in the Android they have similar issue, then I try to publish my library and
yarn
in the application side, it is now working well.