Skip to content

Instantly share code, notes, and snippets.

@andybangs
Last active February 4, 2019 03:03
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save andybangs/c4651a3916ebde0df1c977b220bbec4b to your computer and use it in GitHub Desktop.
Save andybangs/c4651a3916ebde0df1c977b220bbec4b to your computer and use it in GitHub Desktop.
Example RCTEventEmitter Subclass
#import "RCTEventEmitter.h"
#import "RCTBridge.h"
@interface GSEventEmitter : RCTEventEmitter <RCTBridgeModule>
+ (BOOL)application:(UIApplication *)application didSightBeacon:(NSString *)beaconID;
+ (BOOL)application:(UIApplication *)application didDepartBeacon:(NSString *)beaconID;
@end
#import "GSEventEmitter.h"
// Notification/Event Names
NSString *const kBeaconSighted = @"GSEventEmitter/beaconSighted";
NSString *const kBeaconDeparted = @"GSEventEmitter/beaconDeparted";
@implementation GSEventEmitter
RCT_EXPORT_MODULE();
- (NSDictionary<NSString *, NSString *> *)constantsToExport {
return @{ @"BEACON_SIGHTED": kBeaconSighted,
@"BEACON_DEPARTED": kBeaconDeparted,
};
}
- (NSArray<NSString *> *)supportedEvents {
return @[kBeaconSighted,
kBeaconDeparted
];
}
- (void)startObserving {
for (NSString *event in [self supportedEvents]) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleNotification:)
name:event
object:nil];
}
}
- (void)stopObserving {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
# pragma mark Public
+ (BOOL)application:(UIApplication *)application didSightBeacon:(NSString *)beaconID {
[self postNotificationName:kBeaconSighted withPayload:beaconID];
return YES;
}
+ (BOOL)application:(UIApplication *)application didDepartBeacon:(NSString *)beaconID {
[self postNotificationName:kBeaconDeparted withPayload:beaconID];
return YES;
}
# pragma mark Private
+ (void)postNotificationName:(NSString *)name withPayload:(NSObject *)object {
NSDictionary<NSString *, id> *payload = @{@"payload": object};
[[NSNotificationCenter defaultCenter] postNotificationName:name
object:self
userInfo:payload];
}
- (void)handleNotification:(NSNotification *)notification {
[self sendEventWithName:notification.name body:notification.userInfo];
}
@end
@byk04712
Copy link

byk04712 commented Nov 3, 2016

Where declared variable "kBeaconSightingNotification" ?

@paalex
Copy link

paalex commented Nov 10, 2016

What's kBeaconSightingNotification?

@andybangs
Copy link
Author

@byk04712 @paalex Sorry, "kBeaconSightingNotification" was a typo. It should have been "kSightedBeacon". I've updated the gist to correct the typo and to show how to support multiple notifications with a single class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment