Search code examples
iosswiftreact-nativereact-native-modules

Swift NativeModule for iOS is always null


I am building a mobile application using ReactNative for both IOS and Android. I am also building a native module for iOS using Swift. But when I access the module class from JS, it is always returning null.

I created a WaterRowerBleManager.swift file with the following code.

import Foundation

@objc(WaterRowerBleManager)
class WaterRowerBleManager: NSObject {
  @objc
  func constantsToExpose() -> [AnyHashable : Any]! {
    return [
          "number": 123.9,
          "string": "foo",
          "boolean": true,
          "array": [1, 22.2, "33"],
          "object": ["a": 1, "b": 2]
        ]
  }
  
  @objc
  static func requiresMainQueueSetup() -> Bool {
     return true
  }
}

It created a bridge header file with the ".h" extension as well. I have left the file as is.

Then I created a WaterRowerBleManager.m file with the following code.

#import <Foundation/Foundation.h>
#import "React/RCTBridgeModule.h"

@interface RCT_EXTERN_MODULE(WaterRowerBleManager, NSObject)
@end

From the ReactNative, in access the module from App.js as follow.

import { NativeModules } from 'react-native';
NativeModules.WaterRowerBleManager

The NativeModules.WaterRowerBleManager is always returning null. What is wrong with my code and how can I fix it?


Solution

  • You need to create Bridge file and need to export module name to use it.

    in your WaterRowerBleManager.h File

    #import <React/RCTBridgeModule.h>
    

    @interface WaterRowerBleManager : NSObject @end

    in your WaterRowerBleManager.m File

    RCT_EXPORT_MODULE(WaterRowerBleManager);