I'm new in React Native and I would like to use native modules in order to get a battery status of the phone. The problem is that I'm getting fallowing error: @"Bridge module %@
does not conform to RCTBridgeModule". I'm guessing that it is class related but I'm not familiar with a Objective-C syntax. I would really appreciate any help on this field even though the answer is simple. Thank you!
My BatteryStatus.h looks like this:
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
@interface BatteryStatus : RCTEventEmitter <RCTBridgeModule>
@end
My BatteryStatus.m looks like this:
#import "BatteryStatus.h"
@implementation BatteryStatus
RCT_EXPORT_MODULE(BatteryStatus)
- (instancetype)init
{
if ((self = [super init])) {
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
}
return self;
}
RCT_EXPORT_METHOD(hide) {
}
RCT_EXPORT_METHOD(updateBatteryLevel:(RCTResponseSenderBlock)callback)
{
callback(@[[self getBatteryStatus]]);
}
//manually get battery status by calling following method
-(NSDictionary*)getBatteryStatus
{
float batteryLevel = [UIDevice currentDevice].batteryLevel;
NSObject* currentLevel = nil;
currentLevel = [NSNumber numberWithFloat:(batteryLevel * 100)];
NSMutableDictionary* batteryData = [NSMutableDictionary dictionaryWithCapacity:2];
[batteryData setObject:currentLevel forKey:@"level"];
return batteryData;
}
@end
And I'm trying to use it in React Native like this:
import { Text, View, NativeModules } from 'react-native';
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
batteryLevel: null,
};
}
componentDidMount() {
NativeModules.BatteryStatus.updateBatteryLevel((info) => {
console.log(info.level);
const level = Math.ceil(info.level);
this.setState({ batteryLevel: level });
});
}
render() {
return (
<View>
<Text>TEST</Text>
</View>
);
}
}
export default App;