Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 879
Wai Yan Hein Avatar asked Dec 16 '25 13:12

Wai Yan Hein


1 Answers

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);
like image 78
Sunny Shah Avatar answered Dec 19 '25 03:12

Sunny Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!