[fcm] First steps towards identifying the new API for messaging / notifications

This commit is contained in:
Chris Bianca 2018-01-30 11:15:59 +00:00
parent 09fa3b9e31
commit d429db7e86
11 changed files with 535 additions and 2 deletions

View File

@ -17,6 +17,7 @@
8376F7141F7C149100D45A85 /* RNFirebaseFirestoreDocumentReference.m in Sources */ = {isa = PBXBuildFile; fileRef = 8376F70E1F7C149000D45A85 /* RNFirebaseFirestoreDocumentReference.m */; }; 8376F7141F7C149100D45A85 /* RNFirebaseFirestoreDocumentReference.m in Sources */ = {isa = PBXBuildFile; fileRef = 8376F70E1F7C149000D45A85 /* RNFirebaseFirestoreDocumentReference.m */; };
8376F7151F7C149100D45A85 /* RNFirebaseFirestore.m in Sources */ = {isa = PBXBuildFile; fileRef = 8376F7101F7C149000D45A85 /* RNFirebaseFirestore.m */; }; 8376F7151F7C149100D45A85 /* RNFirebaseFirestore.m in Sources */ = {isa = PBXBuildFile; fileRef = 8376F7101F7C149000D45A85 /* RNFirebaseFirestore.m */; };
8376F7161F7C149100D45A85 /* RNFirebaseFirestoreCollectionReference.m in Sources */ = {isa = PBXBuildFile; fileRef = 8376F7111F7C149000D45A85 /* RNFirebaseFirestoreCollectionReference.m */; }; 8376F7161F7C149100D45A85 /* RNFirebaseFirestoreCollectionReference.m in Sources */ = {isa = PBXBuildFile; fileRef = 8376F7111F7C149000D45A85 /* RNFirebaseFirestoreCollectionReference.m */; };
838E36FE201B9169004DCD3A /* NewRNFirebaseMessaging.m in Sources */ = {isa = PBXBuildFile; fileRef = 838E36FD201B9169004DCD3A /* NewRNFirebaseMessaging.m */; };
839D916C1EF3E20B0077C7C8 /* RNFirebaseAdMob.m in Sources */ = {isa = PBXBuildFile; fileRef = 839D914F1EF3E20A0077C7C8 /* RNFirebaseAdMob.m */; }; 839D916C1EF3E20B0077C7C8 /* RNFirebaseAdMob.m in Sources */ = {isa = PBXBuildFile; fileRef = 839D914F1EF3E20A0077C7C8 /* RNFirebaseAdMob.m */; };
839D916D1EF3E20B0077C7C8 /* RNFirebaseAdMobInterstitial.m in Sources */ = {isa = PBXBuildFile; fileRef = 839D91511EF3E20A0077C7C8 /* RNFirebaseAdMobInterstitial.m */; }; 839D916D1EF3E20B0077C7C8 /* RNFirebaseAdMobInterstitial.m in Sources */ = {isa = PBXBuildFile; fileRef = 839D91511EF3E20A0077C7C8 /* RNFirebaseAdMobInterstitial.m */; };
839D916E1EF3E20B0077C7C8 /* RNFirebaseAdMobRewardedVideo.m in Sources */ = {isa = PBXBuildFile; fileRef = 839D91531EF3E20A0077C7C8 /* RNFirebaseAdMobRewardedVideo.m */; }; 839D916E1EF3E20B0077C7C8 /* RNFirebaseAdMobRewardedVideo.m in Sources */ = {isa = PBXBuildFile; fileRef = 839D91531EF3E20A0077C7C8 /* RNFirebaseAdMobRewardedVideo.m */; };
@ -66,6 +67,8 @@
8376F7111F7C149000D45A85 /* RNFirebaseFirestoreCollectionReference.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNFirebaseFirestoreCollectionReference.m; sourceTree = "<group>"; }; 8376F7111F7C149000D45A85 /* RNFirebaseFirestoreCollectionReference.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNFirebaseFirestoreCollectionReference.m; sourceTree = "<group>"; };
8376F7121F7C149000D45A85 /* RNFirebaseFirestoreDocumentReference.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNFirebaseFirestoreDocumentReference.h; sourceTree = "<group>"; }; 8376F7121F7C149000D45A85 /* RNFirebaseFirestoreDocumentReference.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNFirebaseFirestoreDocumentReference.h; sourceTree = "<group>"; };
8376F7131F7C149000D45A85 /* RNFirebaseFirestoreCollectionReference.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNFirebaseFirestoreCollectionReference.h; sourceTree = "<group>"; }; 8376F7131F7C149000D45A85 /* RNFirebaseFirestoreCollectionReference.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNFirebaseFirestoreCollectionReference.h; sourceTree = "<group>"; };
838E36FC201B9169004DCD3A /* NewRNFirebaseMessaging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NewRNFirebaseMessaging.h; sourceTree = "<group>"; };
838E36FD201B9169004DCD3A /* NewRNFirebaseMessaging.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NewRNFirebaseMessaging.m; sourceTree = "<group>"; };
839D914E1EF3E20A0077C7C8 /* RNFirebaseAdMob.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNFirebaseAdMob.h; sourceTree = "<group>"; }; 839D914E1EF3E20A0077C7C8 /* RNFirebaseAdMob.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNFirebaseAdMob.h; sourceTree = "<group>"; };
839D914F1EF3E20A0077C7C8 /* RNFirebaseAdMob.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNFirebaseAdMob.m; sourceTree = "<group>"; }; 839D914F1EF3E20A0077C7C8 /* RNFirebaseAdMob.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNFirebaseAdMob.m; sourceTree = "<group>"; };
839D91501EF3E20A0077C7C8 /* RNFirebaseAdMobInterstitial.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNFirebaseAdMobInterstitial.h; sourceTree = "<group>"; }; 839D91501EF3E20A0077C7C8 /* RNFirebaseAdMobInterstitial.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNFirebaseAdMobInterstitial.h; sourceTree = "<group>"; };
@ -256,6 +259,8 @@
839D91631EF3E20A0077C7C8 /* messaging */ = { 839D91631EF3E20A0077C7C8 /* messaging */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
838E36FC201B9169004DCD3A /* NewRNFirebaseMessaging.h */,
838E36FD201B9169004DCD3A /* NewRNFirebaseMessaging.m */,
839D91641EF3E20A0077C7C8 /* RNFirebaseMessaging.h */, 839D91641EF3E20A0077C7C8 /* RNFirebaseMessaging.h */,
839D91651EF3E20A0077C7C8 /* RNFirebaseMessaging.m */, 839D91651EF3E20A0077C7C8 /* RNFirebaseMessaging.m */,
); );
@ -343,6 +348,7 @@
839D916C1EF3E20B0077C7C8 /* RNFirebaseAdMob.m in Sources */, 839D916C1EF3E20B0077C7C8 /* RNFirebaseAdMob.m in Sources */,
17AF4F6B1F59CDBF00C02336 /* RNFirebaseLinks.m in Sources */, 17AF4F6B1F59CDBF00C02336 /* RNFirebaseLinks.m in Sources */,
8376F7161F7C149100D45A85 /* RNFirebaseFirestoreCollectionReference.m in Sources */, 8376F7161F7C149100D45A85 /* RNFirebaseFirestoreCollectionReference.m in Sources */,
838E36FE201B9169004DCD3A /* NewRNFirebaseMessaging.m in Sources */,
8376F7151F7C149100D45A85 /* RNFirebaseFirestore.m in Sources */, 8376F7151F7C149100D45A85 /* RNFirebaseFirestore.m in Sources */,
839D91701EF3E20B0077C7C8 /* RNFirebaseAuth.m in Sources */, 839D91701EF3E20B0077C7C8 /* RNFirebaseAuth.m in Sources */,
8323CF091F6FBD870071420B /* RNFirebaseAdMobNativeExpressManager.m in Sources */, 8323CF091F6FBD870071420B /* RNFirebaseAdMobNativeExpressManager.m in Sources */,

View File

@ -32,7 +32,10 @@ static NSString *const STORAGE_DOWNLOAD_SUCCESS = @"download_success";
static NSString *const STORAGE_DOWNLOAD_FAILURE = @"download_failure"; static NSString *const STORAGE_DOWNLOAD_FAILURE = @"download_failure";
// Messaging // Messaging
static NSString *const MESSAGING_MESSAGE_RECEIVED = @"messaging_message_received";
static NSString *const MESSAGING_TOKEN_REFRESHED = @"messaging_token_refreshed"; static NSString *const MESSAGING_TOKEN_REFRESHED = @"messaging_token_refreshed";
// TODO: Remove
static NSString *const MESSAGING_NOTIFICATION_RECEIVED = @"messaging_notification_received"; static NSString *const MESSAGING_NOTIFICATION_RECEIVED = @"messaging_notification_received";
// AdMob // AdMob

View File

@ -0,0 +1,23 @@
#ifndef NewRNFirebaseMessaging_h
#define NewRNFirebaseMessaging_h
#import <Foundation/Foundation.h>
#if __has_include(<FirebaseMessaging/FirebaseMessaging.h>)
#import <FirebaseMessaging/FirebaseMessaging.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
@interface NewRNFirebaseMessaging : RCTEventEmitter<RCTBridgeModule, FIRMessagingDelegate>
#if !TARGET_OS_TV
#endif
@end
#else
@interface NewRNFirebaseMessaging : NSObject
@end
#endif
#endif

View File

@ -0,0 +1,132 @@
#import "NewRNFirebaseMessaging.h"
#if __has_include(<FirebaseMessaging/FirebaseMessaging.h>)
@import UserNotifications;
#import "RNFirebaseEvents.h"
#import "RNFirebaseUtil.h"
#import <FirebaseMessaging/FirebaseMessaging.h>
#import <FirebaseInstanceID/FIRInstanceID.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTConvert.h>
#import <React/RCTUtils.h>
@interface NewRNFirebaseMessaging ()
@end
@implementation NewRNFirebaseMessaging
RCT_EXPORT_MODULE()
- (id)init {
self = [super init];
if (self != nil) {
NSLog(@"Setting up RNFirebaseMessaging instance");
[self initialiseMessaging];
}
return self;
}
- (void)initialiseMessaging {
// Establish Firebase managed data channel
[FIRMessaging messaging].shouldEstablishDirectChannel = YES;
}
- (void)dealloc {
}
// ** Start React Module methods **
RCT_EXPORT_METHOD(getToken:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
resolve([[FIRInstanceID instanceID] token]);
}
RCT_EXPORT_METHOD(requestPermission:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
if (RCTRunningInAppExtension()) {
reject(@"request_permission_unavailable", @"requestPermission is not supported in App Extensions", nil);
return;
}
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
UIUserNotificationType types = (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
[RCTSharedApplication() registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:types categories:nil]];
// Unfortunately on iOS 9 or below, there's no way to tell whether the user accepted or
// rejected the permissions popup
// TODO: Is there something we can listen for?
resolve(@{@"status":@"unknown"});
} else {
// iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// For iOS 10 display notification (sent via APNS)
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
resolve(@{@"status": @"granted"});
} else {
reject(@"permission_error", @"Failed to grant permission", error);
}
}];
#endif
}
dispatch_async(dispatch_get_main_queue(), ^{
[RCTSharedApplication() registerForRemoteNotifications];
});
}
// Non Web SDK methods
RCT_EXPORT_METHOD(deleteInstanceId:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
[[FIRInstanceID instanceID] deleteIDWithHandler:^(NSError * _Nullable error) {
if (!error) {
resolve(nil);
} else {
reject(@"instance_id_error", @"Failed to delete instance id", error);
}
}];
}
RCT_EXPORT_METHOD(getBadgeNumber: (RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
resolve(@([RCTSharedApplication() applicationIconBadgeNumber]));
}
RCT_EXPORT_METHOD(getInitialNotification:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
UILocalNotification *localUserInfo = [self bridge].launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
if (localUserInfo) {
resolve([[localUserInfo userInfo] copy]);
} else {
resolve([[self bridge].launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] copy]);
}
}
RCT_EXPORT_METHOD(subscribeToTopic: (NSString*) topic) {
[[FIRMessaging messaging] subscribeToTopic:topic];
}
RCT_EXPORT_METHOD(unsubscribeFromTopic: (NSString*) topic) {
[[FIRMessaging messaging] unsubscribeFromTopic:topic];
}
RCT_EXPORT_METHOD(setBadgeNumber: (NSInteger*) number) {
dispatch_async(dispatch_get_main_queue(), ^{
[RCTSharedApplication() setApplicationIconBadgeNumber:*number];
});
}
- (NSArray<NSString *> *)supportedEvents {
return @[MESSAGING_MESSAGE_RECEIVED, MESSAGING_TOKEN_REFRESHED];
}
+ (BOOL)requiresMainQueueSetup
{
return YES;
}
@end
#else
@implementation NewRNFirebaseMessaging
@end
#endif

View File

@ -20,6 +20,9 @@ import Database, { NAMESPACE as DatabaseNamespace } from '../database';
import Firestore, { NAMESPACE as FirestoreNamespace } from '../firestore'; import Firestore, { NAMESPACE as FirestoreNamespace } from '../firestore';
import Links, { NAMESPACE as LinksNamespace } from '../links'; import Links, { NAMESPACE as LinksNamespace } from '../links';
import Messaging, { NAMESPACE as MessagingNamespace } from '../messaging'; import Messaging, { NAMESPACE as MessagingNamespace } from '../messaging';
import NewMessaging, {
NAMESPACE as NewMessagingNamespace,
} from '../messaging/messagingIndex';
import Performance, { NAMESPACE as PerfNamespace } from '../perf'; import Performance, { NAMESPACE as PerfNamespace } from '../perf';
import Storage, { NAMESPACE as StorageNamespace } from '../storage'; import Storage, { NAMESPACE as StorageNamespace } from '../storage';
import Utils, { NAMESPACE as UtilsNamespace } from '../utils'; import Utils, { NAMESPACE as UtilsNamespace } from '../utils';
@ -46,6 +49,7 @@ export default class App {
firestore: () => Firestore; firestore: () => Firestore;
links: () => Links; links: () => Links;
messaging: () => Messaging; messaging: () => Messaging;
newmessaging: () => NewMessaging;
perf: () => Performance; perf: () => Performance;
storage: () => Storage; storage: () => Storage;
utils: () => Utils; utils: () => Utils;
@ -85,6 +89,11 @@ export default class App {
this.firestore = APPS.appModule(this, FirestoreNamespace, Firestore); this.firestore = APPS.appModule(this, FirestoreNamespace, Firestore);
this.links = APPS.appModule(this, LinksNamespace, Links); this.links = APPS.appModule(this, LinksNamespace, Links);
this.messaging = APPS.appModule(this, MessagingNamespace, Messaging); this.messaging = APPS.appModule(this, MessagingNamespace, Messaging);
this.newmessaging = APPS.appModule(
this,
NewMessagingNamespace,
NewMessaging
);
this.perf = APPS.appModule(this, PerfNamespace, Performance); this.perf = APPS.appModule(this, PerfNamespace, Performance);
this.storage = APPS.appModule(this, StorageNamespace, Storage); this.storage = APPS.appModule(this, StorageNamespace, Storage);
this.utils = APPS.appModule(this, UtilsNamespace, Utils); this.utils = APPS.appModule(this, UtilsNamespace, Utils);

View File

@ -47,6 +47,10 @@ import {
statics as MessagingStatics, statics as MessagingStatics,
MODULE_NAME as MessagingModuleName, MODULE_NAME as MessagingModuleName,
} from '../messaging'; } from '../messaging';
import {
statics as NewMessagingStatics,
MODULE_NAME as NewMessagingModuleName,
} from '../messaging/messagingIndex';
import { import {
statics as PerformanceStatics, statics as PerformanceStatics,
MODULE_NAME as PerfModuleName, MODULE_NAME as PerfModuleName,
@ -72,6 +76,7 @@ import type {
FirestoreModule, FirestoreModule,
LinksModule, LinksModule,
MessagingModule, MessagingModule,
NewMessagingModule,
PerformanceModule, PerformanceModule,
StorageModule, StorageModule,
UtilsModule, UtilsModule,
@ -90,6 +95,7 @@ class Firebase {
firestore: FirestoreModule; firestore: FirestoreModule;
links: LinksModule; links: LinksModule;
messaging: MessagingModule; messaging: MessagingModule;
newmessaging: NewMessagingModule;
perf: PerformanceModule; perf: PerformanceModule;
storage: StorageModule; storage: StorageModule;
utils: UtilsModule; utils: UtilsModule;
@ -137,6 +143,11 @@ class Firebase {
MessagingStatics, MessagingStatics,
MessagingModuleName MessagingModuleName
); );
this.newmessaging = APPS.moduleAndStatics(
'newmessaging',
NewMessagingStatics,
NewMessagingModuleName
);
this.perf = APPS.moduleAndStatics( this.perf = APPS.moduleAndStatics(
'perf', 'perf',
PerformanceStatics, PerformanceStatics,

View File

@ -0,0 +1,186 @@
/**
* @flow
* Messaging (FCM) representation wrapper
*/
import { SharedEventEmitter } from '../../utils/events';
import INTERNALS from '../../utils/internals';
import { getLogger } from '../../utils/log';
import ModuleBase from '../../utils/ModuleBase';
import { getNativeModule } from '../../utils/native';
import { isFunction, isObject } from '../../utils';
import type App from '../core/firebase-app';
type Message = {
// TODO
};
type OnMessage = Message => any;
type OnMessageObserver = {
next: OnMessage,
};
type OnTokenRefresh = String => any;
type OnTokenRefreshObserver = {
next: OnTokenRefresh,
};
type RemoteMessage = {
// TODO
};
const NATIVE_EVENTS = [
'messaging_message_received',
'messaging_token_refreshed',
];
export const MODULE_NAME = 'NewRNFirebaseMessaging';
export const NAMESPACE = 'newmessaging';
/**
* @class Messaging
*/
export default class Messaging extends ModuleBase {
constructor(app: App) {
super(app, {
events: NATIVE_EVENTS,
moduleName: MODULE_NAME,
multiApp: false,
namespace: NAMESPACE,
});
SharedEventEmitter.addListener(
// sub to internal native event - this fans out to
// public event name: onMessage
'messaging_message_received',
(message: Message) => {
SharedEventEmitter.emit('onMessage', message);
}
);
SharedEventEmitter.addListener(
// sub to internal native event - this fans out to
// public event name: onMessage
'messaging_token_refreshed',
(token: string) => {
SharedEventEmitter.emit('onTokenRefresh', token);
}
);
}
deleteToken(token: string): Promise<void> {
return getNativeModule(this).deleteToken(token);
}
getToken(): Promise<string> {
return getNativeModule(this).getToken();
}
onMessage(nextOrObserver: OnMessage | OnMessageObserver): () => any {
let listener;
if (isFunction(nextOrObserver)) {
listener = nextOrObserver;
} else if (isObject(nextOrObserver) && isFunction(nextOrObserver.next)) {
listener = nextOrObserver.next;
} else {
throw new Error(
'Messaging.onMessage failed: First argument must be a function or observer object with a `next` function.'
);
}
// TODO: iOS finish
getLogger(this).info('Creating onMessage listener');
SharedEventEmitter.addListener('onMessage', listener);
return () => {
getLogger(this).info('Removing onMessage listener');
SharedEventEmitter.removeListener('onMessage', listener);
};
}
onTokenRefresh(
nextOrObserver: OnTokenRefresh | OnTokenRefreshObserver
): () => any {
let listener;
if (isFunction(nextOrObserver)) {
listener = nextOrObserver;
} else if (isObject(nextOrObserver) && isFunction(nextOrObserver.next)) {
listener = nextOrObserver.next;
} else {
throw new Error(
'Messaging.OnTokenRefresh failed: First argument must be a function or observer object with a `next` function.'
);
}
getLogger(this).info('Creating onTokenRefresh listener');
SharedEventEmitter.addListener('onTokenRefresh', listener);
return () => {
getLogger(this).info('Removing onTokenRefresh listener');
SharedEventEmitter.removeListener('onTokenRefresh', listener);
};
}
requestPermission(): Promise<void> {
return getNativeModule(this).requestPermission();
}
/**
* NON WEB-SDK METHODS
*/
deleteInstanceId(): Promise<void> {
return getNativeModule(this).deleteInstanceId();
}
getBadgeNumber(): Promise<number> {
return getNativeModule(this).getBadgeNumber();
}
getInitialMessage(): Promise<Message> {
return getNativeModule(this).getInitialMessage();
}
sendMessage(remoteMessage: RemoteMessage): Promise<void> {
return getNativeModule(this).send(remoteMessage);
}
setBadgeNumber(badge: number): void {
getNativeModule(this).setBadgeNumber(badge);
}
subscribeToTopic(topic: string): void {
getNativeModule(this).subscribeToTopic(topic);
}
unsubscribeFromTopic(topic: string): void {
getNativeModule(this).unsubscribeFromTopic(topic);
}
/**
* KNOWN UNSUPPORTED METHODS
*/
setBackgroundMessageHandler() {
throw new Error(
INTERNALS.STRINGS.ERROR_UNSUPPORTED_MODULE_METHOD(
'messaging',
'setBackgroundMessageHandler'
)
);
}
useServiceWorker() {
throw new Error(
INTERNALS.STRINGS.ERROR_UNSUPPORTED_MODULE_METHOD(
'messaging',
'useServiceWorker'
)
);
}
}
export const statics = {
// RemoteMessage,
};

View File

@ -0,0 +1,138 @@
/**
* @flow
* Messaging (FCM) representation wrapper
*/
import { SharedEventEmitter } from '../../utils/events';
import { getLogger } from '../../utils/log';
import ModuleBase from '../../utils/ModuleBase';
import { getNativeModule } from '../../utils/native';
import { isFunction, isObject } from '../../utils';
import type App from '../core/firebase-app';
type CreateNotification = {
// TODO
};
type Notification = {
// TODO
};
type OnNotification = Notification => any;
type OnNotificationObserver = {
next: OnNotification,
};
const NATIVE_EVENTS = ['notifications_notification_received'];
export const MODULE_NAME = 'RNFirebaseNotifications';
export const NAMESPACE = 'notifications';
/**
* @class Notifications
*/
export default class Notifications extends ModuleBase {
constructor(app: App) {
super(app, {
events: NATIVE_EVENTS,
moduleName: MODULE_NAME,
multiApp: false,
namespace: NAMESPACE,
});
SharedEventEmitter.addListener(
// sub to internal native event - this fans out to
// public event name: onMessage
'notifications_notification_received',
(notification: Notification) => {
SharedEventEmitter.emit('onNotification', notification);
}
);
}
/**
* Cancel a local notification by id - using '*' will cancel
* all local notifications.
* @param id
* @returns {*}
*/
cancelNotification(id: string): Promise<void> {
if (!id) return Promise.reject(new Error('Missing notification id'));
if (id === '*') return getNativeModule(this).cancelAllLocalNotifications();
return getNativeModule(this).cancelLocalNotification(id);
}
/**
* Create and display a local notification
* @param notification
* @returns {*}
*/
createNotification(notification: CreateNotification): Promise<void> {
const _notification = Object.assign({}, notification);
_notification.id = _notification.id || new Date().getTime().toString();
_notification.local_notification = true;
return getNativeModule(this).createLocalNotification(_notification);
}
/**
* Returns an array of all scheduled notifications
* @returns {Promise.<Array>}
*/
getScheduledNotifications(): Promise<Object[]> {
return getNativeModule(this).getScheduledLocalNotifications();
}
onNotification(
nextOrObserver: OnNotification | OnNotificationObserver
): () => any {
let listener;
if (isFunction(nextOrObserver)) {
listener = nextOrObserver;
} else if (isObject(nextOrObserver) && isFunction(nextOrObserver.next)) {
listener = nextOrObserver.next;
} else {
throw new Error(
'Notifications.onNotification failed: First argument must be a function or observer object with a `next` function.'
);
}
// TODO: iOS finish
getLogger(this).info('Creating onNotification listener');
SharedEventEmitter.addListener('onNotification', listener);
return () => {
getLogger(this).info('Removing onNotification listener');
SharedEventEmitter.removeListener('onNotification', listener);
};
}
/**
* Remove a delivered notification - using '*' will remove
* all delivered notifications.
* @param id
* @returns {*}
*/
removeDeliveredNotification(id: string): Promise<void> {
if (!id) return Promise.reject(new Error('Missing notification id'));
if (id === '*') {
return getNativeModule(this).removeAllDeliveredNotifications();
}
return getNativeModule(this).removeDeliveredNotification(id);
}
/**
*
* @param notification
* @returns {*}
*/
scheduleNotification(notification: CreateNotification): Promise<void> {
const _notification = Object.assign({}, notification);
if (!notification.id)
return Promise.reject(
new Error('An id is required to schedule a local notification.')
);
_notification.local_notification = true;
return getNativeModule(this).scheduleLocalNotification(_notification);
}
}

View File

@ -19,6 +19,8 @@ import type Links from '../modules/links';
import { typeof statics as LinksStatics } from '../modules/links'; import { typeof statics as LinksStatics } from '../modules/links';
import type Messaging from '../modules/messaging'; import type Messaging from '../modules/messaging';
import { typeof statics as MessagingStatics } from '../modules/messaging'; import { typeof statics as MessagingStatics } from '../modules/messaging';
import type NewMessaging from '../modules/messaging/messagingIndex';
import { typeof statics as NewMessagingStatics } from '../modules/messaging/messagingIndex';
import type ModuleBase from '../utils/ModuleBase'; import type ModuleBase from '../utils/ModuleBase';
import type Performance from '../modules/perf'; import type Performance from '../modules/perf';
import { typeof statics as PerformanceStatics } from '../modules/perf'; import { typeof statics as PerformanceStatics } from '../modules/perf';
@ -58,6 +60,8 @@ export type FirebaseModuleName =
| 'RNFirebaseFirestore' | 'RNFirebaseFirestore'
| 'RNFirebaseLinks' | 'RNFirebaseLinks'
| 'RNFirebaseMessaging' | 'RNFirebaseMessaging'
| 'NewRNFirebaseMessaging'
| 'RNFirebaseNotifications'
| 'RNFirebasePerformance' | 'RNFirebasePerformance'
| 'RNFirebaseStorage' | 'RNFirebaseStorage'
| 'RNFirebaseUtils'; | 'RNFirebaseUtils';
@ -73,6 +77,8 @@ export type FirebaseNamespace =
| 'firestore' | 'firestore'
| 'links' | 'links'
| 'messaging' | 'messaging'
| 'newmessaging'
| 'notifications'
| 'perf' | 'perf'
| 'storage' | 'storage'
| 'utils'; | 'utils';
@ -217,6 +223,11 @@ export type MessagingModule = {
nativeModuleExists: boolean, nativeModuleExists: boolean,
} & MessagingStatics; } & MessagingStatics;
export type NewMessagingModule = {
(): NewMessaging,
nativeModuleExists: boolean,
} & NewMessagingStatics;
/* Performance types */ /* Performance types */
export type PerformanceModule = { export type PerformanceModule = {

View File

@ -164,7 +164,7 @@ PODS:
- React/Core - React/Core
- React/fishhook - React/fishhook
- React/RCTBlob - React/RCTBlob
- RNFirebase (3.2.0): - RNFirebase (3.2.2):
- React - React
- yoga (0.52.0.React) - yoga (0.52.0.React)
@ -228,7 +228,7 @@ SPEC CHECKSUMS:
nanopb: 5601e6bca2dbf1ed831b519092ec110f66982ca3 nanopb: 5601e6bca2dbf1ed831b519092ec110f66982ca3
Protobuf: 8a9838fba8dae3389230e1b7f8c104aa32389c03 Protobuf: 8a9838fba8dae3389230e1b7f8c104aa32389c03
React: 61a6bdf17a9ff16875c230e6ff278d9de274e16c React: 61a6bdf17a9ff16875c230e6ff278d9de274e16c
RNFirebase: 22b1917fec663706907bc901ed665ac4f8b9bfd6 RNFirebase: 5cf5405d1b67c9720ce63a2da3d6d5346415d0f7
yoga: 646606bf554d54a16711f35596178522fbc00480 yoga: 646606bf554d54a16711f35596178522fbc00480
PODFILE CHECKSUM: 67c98bcb203cb992da590bcab6f690f727653ca5 PODFILE CHECKSUM: 67c98bcb203cb992da590bcab6f690f727653ca5

View File

@ -7,6 +7,20 @@ import DatabaseContents from './tests/support/DatabaseContents';
RNfirebase.database.enableLogging(true); RNfirebase.database.enableLogging(true);
RNfirebase.firestore.enableLogging(true); RNfirebase.firestore.enableLogging(true);
RNfirebase.newmessaging()
.requestPermission()
.then(response => {
console.log('requestPermission:', response);
RNfirebase.newmessaging()
.getToken()
.then(token => {
console.log('token: ', token);
});
})
.catch(error => {
console.error('requestPermission:', error);
});
const config = { const config = {
apiKey: 'AIzaSyDnVqNhxU0Biit9nCo4RorAh5ulQQwko3E', apiKey: 'AIzaSyDnVqNhxU0Biit9nCo4RorAh5ulQQwko3E',
authDomain: 'rnfirebase-b9ad4.firebaseapp.com', authDomain: 'rnfirebase-b9ad4.firebaseapp.com',