3

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?

Chris
  • 321
  • 3
  • 15

1 Answers1

2

I had this problem until I removed my own initializer code. If you need configuration, I recommend you use RCT_EXPORT_METHOD to call in and prepare your module.

Calvin Flegal
  • 185
  • 1
  • 1
  • 10
  • Thanks for this, you're absolutely right. Manually instantiating my bridge module was the reason the bridge was always nil. – Colin Ramsay Jan 24 '16 at 16:15
  • I am currently facing the same issue. How do I access my module (from Obj-C) without instantiating it, i.e. is there a hook or something to the module when it is instantiated by the system? Kind of stuck in this and your question looked the most like my situation. – stephanmantel Jan 10 '17 at 09:51
  • @stephanmantel AFAIK there's not...you can create your own config method using `RCT_EXPORT_METHOD`. As usual, mind the information in the guides about not making thread assumptions, etc – Calvin Flegal Jan 11 '17 at 16:15