Interview frequency: …
Short answer
Create a Swift class with the desired methods, use an Objective-C bridging file, and register it in the React Native module tree with the RCT_EXTERN_MODULE macro.
Explanation
Since the old React Native core relies on Objective-C, connecting Swift code requires a small Objective-C file to export the class and methods using RCT_EXTERN_MODULE and RCT_EXTERN_METHOD, and to specify whether the module needs to run on the Main Queue or a separate thread. This approach belongs to the old architecture; new projects should prefer Turbo Native Modules with Codegen.
Code example
// Swift file:
@objc(BatteryModule)
class BatteryModule: NSObject {
@objc(getBatteryLevel:rejecter:)
func getBatteryLevel(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
resolve(UIDevice.current.batteryLevel * 100)
}
}
// Objective-C file that exports it (BatteryModule.m):
#import <React/RCTBridgeModule.h>
@interface RCT_EXTERN_MODULE(BatteryModule, NSObject)
RCT_EXTERN_METHOD(getBatteryLevel:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
@endCommon mistakes
- Forgetting to add @objc before Swift classes and methods, preventing the Objective-C runtime from seeing them.