3

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372

2 Answers2

1

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);
Sunny Shah
  • 12,990
  • 9
  • 50
  • 86
1

Met the same problem here. Found the main reason is that ReactNative will not load your NativeModule if you did not expose any method in it. So the solution is to capsule some methods in .m and rebuild/reload.

Wu Tora
  • 11
  • 1