【发布时间】:2015-11-30 22:51:14
【问题描述】:
我正在创建自己的自定义组件,以与蓝牙设备进行交互。 I tried this in Swift,但由于访问网桥的问题而没有到达任何地方。
我在 Objective-C 中重新实现了它并遇到了同样的问题 (bridge = nil)。为了修复它,我使用了:
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"];
}
添加到我的Bridging-Header.h:
#import "BTAdapter.h"
我在 Swift 中这样称呼它:
let adapter: BTAdapter = BTAdapter()
adapter.sendEvent("TestEvent")
这是一件坏事吗?我在类似主题上关注了一个相当过时的 React Native GitHub 问题,但围绕这个解决方案并没有太多确定性。 This seems to suggest it's not a good idea at all.
这里有什么问题?
【问题讨论】:
标签: ios objective-c react-native