I'm doing something Async in an iOS app. It's triggered by javascript. When it's done (somewhere separated in app), I want to let javascript know.
My current solution is a native module inherited from RCTEventEmitter
, which has the following method:
@interface MyEventEmitter : RCTEventEmitter
// ...
end
@implementation
- (void)giveSomethingToJS:(NSString *)something {
[self sendEventWithName:@"SOME_NAME" body:something];
}
@end
Then, when my Async job's done, I call this method:
MyEventEmitter *emitter = [[MyEventEmitter alloc] init];
[emitter giveSomethingToJS:@{}];
And obviously, emitter.bridge
is nil and the app crashed because of assert bridge != nil
. So how am I supposed to get the bridge and let *emitter
(the instance) know. Or how can I get the right instance with bridge initialized?
Thanks in advance!
I'm doing something Async in an iOS app. It's triggered by javascript. When it's done (somewhere separated in app), I want to let javascript know.
My current solution is a native module inherited from RCTEventEmitter
, which has the following method:
@interface MyEventEmitter : RCTEventEmitter
// ...
end
@implementation
- (void)giveSomethingToJS:(NSString *)something {
[self sendEventWithName:@"SOME_NAME" body:something];
}
@end
Then, when my Async job's done, I call this method:
MyEventEmitter *emitter = [[MyEventEmitter alloc] init];
[emitter giveSomethingToJS:@{}];
And obviously, emitter.bridge
is nil and the app crashed because of assert bridge != nil
. So how am I supposed to get the bridge and let *emitter
(the instance) know. Or how can I get the right instance with bridge initialized?
Thanks in advance!
Share Improve this question edited Jul 20, 2016 at 2:13 jsondwyer 4378 silver badges18 bronze badges asked Jul 20, 2016 at 1:26 Arthur WangArthur Wang 1312 silver badges8 bronze badges2 Answers
Reset to default 6The issue is that in the React-Native iOS SDK, RCTEventEmitter
subclasses should not be initialized by you. The React-Native SDK actually handles initialization of your RCTEventEmitters.
As Arthur points out, using NSNotificationCenter
to municate with your RCTEventEmitter
is a good strategy. You can also create a custom singleton class and register RCTEventEmitter's with it on initialization if you need pointers to these event emitters.
I have a quick fix, not a very good idea but achieved what I want.
The problem is I can't get THE instance of MyEventEmitter
, so I instead use notification center in native code to notify THE instance.
[[NSNotificationCenter defaultCenter] addObserverForName:@"NATIVE_WEIXIN_LOGIN_RESP_CODE"
object:nil
queue:nil
usingBlock:^(NSNotification * _Nonnull notification) {
SendAuthResp *resp = notification.object;
[self sendEventWithName:@"WEIXIN_LOGIN_RESP_CODE" body:resp.code];
}];
Can you still post what the correct way in React Native to do what I want?