Skip to content

Instantly share code, notes, and snippets.

@kmdarshan
Last active August 14, 2017 03:06
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kmdarshan/0910d6d130badec29744792bf99e3b6d to your computer and use it in GitHub Desktop.
Sending a notification from react native objective code to Javascript and Vice verada
//
// EventManager.h
//
// Created by md on 6/14/17.
//
//
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
@interface EventManager : RCTEventEmitter <RCTBridgeModule>
@end
//
// EventManager.m
//
// Created by md on 6/14/17.
//
//
#import "EventManager.h"
@interface EventManager ()
@end
@implementation EventManager
RCT_EXPORT_MODULE();
- (NSArray<NSString *> *)supportedEvents {
// this is the list of supported events.
return @[@"scrollToTopHomeFeed"];
}
- (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];
}
// Use this method to handle notifications from the javascript side
- (void)handleNotification:(NSNotification *)notification {
if([notification.name isEqualToString:@"scrollToTopHomeFeed"])
{
[self sendEventWithName:notification.name body:@"scrollToTopHomeFeed"];
}
else
{
[self sendEventWithName:notification.name body:notification.userInfo];
}
}
@end
// This is your javascript code
import { NativeModules, NativeEventEmitter } from 'react-native';
// In this method add a listener to your notifications.
componentDidMount() {
const { EventManager } = NativeModules;
this.eventEmitter = new NativeEventEmitter(EventManager);
this.eventEmitter.addListener('scrollToTopHomeFeed', (data) => this.scrollToTop(data))
}
scrollToTop(data) {
this.flatList.getScrollResponder().scrollTo({x:0, y:0, animated: true})
}
//
// NotificationManager.h
//
// Created by md on 6/14/17.
//
//
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
@interface NotificationManager : NSObject <RCTBridgeModule>
@end
//
// NotificationManager.m
//
// Created by md on 6/14/17.
//
//
#import "NotificationManager.h"
#import "EventManager.h"
#import <React/RCTEventEmitter.h>
@implementation NotificationManager
RCT_EXPORT_MODULE()
RCT_EXPORT_METHOD(postNotification:(NSString *)name) {
[[NSNotificationCenter defaultCenter] postNotificationName:name object:nil userInfo:nil];
}
@end
import { NativeModules, NativeEventEmitter } from 'react-native';
var NotificationManager = require('react-native').NativeModules.NotificationManager;
// This is how you will post a notification to objective-c code.
NotificationManager.postNotification("scrollToTopHomeFeed")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment