I am working through creating my own custom component, to interact with a Bluetooth device. I tried this in Swift, but didn't get anywhere due to problems with accessing the bridge.
I reimplemented it in Objective-C and experienced the same problem (bridge = nil
). To fix it, I used:
BTAdapter.h
#import "RCTBridgeModule.h"
@interface BTAdapter : NSObject<RCTBridgeModule>
- (void)sendEvent:(NSString *)name;
@end
BTAdapter.m
#import "BTAdapter.h"
#import "RCTBridge.h"
#import "RCTEventDispatcher.h"
@implementation BTAdapter
RCT_EXPORT_MODULE()
@synthesize bridge = _bridge;
+ (id)allocWithZone:(NSZone *) zone
{
static BTAdapter *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [super allocWithZone:zone];
});
return sharedInstance;
}
- (void)sendEvent:(NSString *)name
{
NSLog(@"Received generic event in the bridge");
if (self.bridge == nil) {
NSLog(@"Bridge is nil"); // This happens normally
} else {
NSLog(@"Bridge is NOT nil"); // This happens with a singleton
}
[self.bridge.eventDispatcher sendAppEventWithName:name body:@"Event from the bridge"];
}
Add to my Bridging-Header.h
:
#import "BTAdapter.h"
And I'm calling it in Swift like:
let adapter: BTAdapter = BTAdapter()
adapter.sendEvent("TestEvent")
Is this a bad thing to do? I followed a pretty outdated React Native GitHub issue on a similar topic, but there wasn't a whole lot of certainty surrounding this solution. This seems to suggest it's not a good idea at all.
What is wrong here?