但我注意到,每当我从另一个方法调用它时,我的桥变量为 nil。我相信这是因为仅在从 javascript 调用桥接方法时才设置桥接。我已经尝试了从创建委托(delegate)到创建 SingleTon 类的所有方法。以上都不起作用,我无法弄清楚为什么它只能在我从 Javascript 调用的方法中使用。这是我的课
Helper.h
#import "RCTBridge.h"
#import "AppDelegate.h"
#import "RCTEventEmitter.h"
@interface Helper : RCTEventEmitter <RCTBridgeModule>
-(void) auth;
@end
这是我的 .m 文件: Helper.m
#import "AppDelegate.h"
#import "Helper.h"
#import "RCTBridge.h"
#import "RCTEventDispatcher.h"
@implementation Helper
RCT_EXPORT_MODULE();
@synthesize bridge = _bridge;
- (NSArray<NSString *> *)supportedEvents {
return @[@"SpotifyHelper"];
}
RCT_EXPORT_METHOD(auth)
{
[self.bridge.eventDispatcher sendDeviceEventWithName:@"SpotifyHelper" body:@{@"Login": @true}];
printf("Auth");
}
RCT_EXPORT_METHOD(play:(NSString *) uri first: id)
{
AppDelegate *appDelegate = [[AppDelegate alloc] init];
[appDelegate play:uri second:id];
}
@end
我像这样从委托(delegate)内部调用该方法:
[[AppDelegate alloc] init] auth]
这就是我认为它未初始化的原因。我不确定如何让 RCTBridge 变量不为零。有帮助吗?
最佳答案
问题出在这里:
[[AppDelegate alloc] init] auth]
当您使用宏 RCT_EXPORT_MODULE()
时,React-Native 将为您实例化该类,任何后续的 alloc/init
都会创建新实例,与原始实例无关.在这些新实例中不会实例化桥。
您可以使用 NSNotifications 解决您的问题。
Helper.h:
#import "RCTEventEmitter.h"
@interface Helper : RCTEventEmitter
+ (void)emitEventWithName:(NSString *)name andPayload:(NSDictionary *)payload;
@end
Helper.m:
#import "Helper.h"
@implementation Helper
RCT_EXPORT_MODULE();
- (NSArray<NSString *> *)supportedEvents {
return @[@"SpotifyHelper"];
}
- (void)startObserving
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(emitEventInternal:)
name:@"event-emitted"
object:nil];
}
- (void)stopObserving
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)emitEventInternal:(NSNotification *)notification
{
[self sendEventWithName:@"SpotifyHelper"
body:notification.userInfo];
}
+ (void)emitEventWithName:(NSString *)name andPayload:(NSDictionary *)payload
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"event-emitted"
object:self
userInfo:payload];
}
// Remaining methods
@end
这里有一个很长的讨论线程:What is the method can be used to send an event from native module to JS
关于javascript - 当我从另一个方法调用方法时,React-native Bridge 为 Nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38818287/