Я пытаюсь заставить push-уведомления / firebase messaging
работать с реагировать на родную - я прошел проверку / запрос разрешения, и я реализовал onMessage
, но я не получаю ни одного из моих тестовых сообщений (отправлено с консоли разработчика firebase
онлайн, в разделе cloud messaging
).Одна странность в том, что когда я проверяю статус сообщения completed
, в нем говорится, что сообщения не отправлялись (0 sent
), поэтому я даже не знаю, получает ли мое приложение шанс получить тестовое сообщение.Вот мой код:
HomeScreen.js (маршрут по умолчанию для корневого навигатора)
export default class HomeScreen extends React.Component {
....
componentDidMount() {
firebase.messaging()
.hasPermission()
.then(enabled => {
if (!enabled) {
this._getPermission();
}
firebase.messaging().getToken()
.then(fcmToken => {
if (fcmToken) {
// user has a device token
} else {
alert("User doesn't have a token yet");
}
}).catch((error) => {
alert(error);
});
firebase.messaging().subscribeToTopic('all').catch((error) => {alert(error)});
this.onTokenRefreshListener = firebase.messaging().onTokenRefresh(fcmToken => {
// Process your token as required
});
this.messageListener = firebase.messaging().onMessage((message: RemoteMessage) => {
// Process your message as required
alert(message);
});
}).catch((error) => {alert(error)});
}
_getPermission = () => {
firebase.messaging()
.requestPermission()
.catch(error => {
// User has rejected permissions
this._getPermission();
});
};
....
componentWillUnmount() {
this.onTokenRefreshListener();
this.messageListener();
firebase.messaging().unsubscribeFromTopic('all');
}
....
AppDelegate.h
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import <UIKit/UIKit.h>
@import UserNotifications;
@interface AppDelegate : UIResponder <UIApplicationDelegate, UNUserNotificationCenterDelegate>
@property (nonatomic, strong) UIWindow *window;
@end
AppDelegate.m
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "AppDelegate.h"
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import "RNFirebaseNotifications.h"
#import "RNFirebaseMessaging.h"
#import <Firebase.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure];
[RNFirebaseNotifications configure];
NSURL *jsCodeLocation;
for (NSString* family in [UIFont familyNames])
{
NSLog(@"%@", family);
for (NSString* name in [UIFont fontNamesForFamilyName: family])
{
NSLog(@" %@", name);
}
}
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"snagit"
initialProperties:nil
launchOptions:launchOptions];
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
return YES;
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[[RNFirebaseNotifications instance] didReceiveLocalNotification:notification];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
[[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
[[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings];
}
@end
Мои BUNDLE_ID
все выглядят правильно.Почему сообщения не отправляются в первую очередь и / или почему я их не получаю?
ОБНОВЛЕНИЕ
Поможет ли попытка FCM?https://github.com/evollu/react-native-fcm
ОБНОВЛЕНИЕ
Мой запрос был неудачным, я получил curl
попытку работать с:
curl -i-H 'Тип контента: application / json' -H 'Авторизация: ключ = ключ сервера' -XPOST https://fcm.googleapis.com/fcm/send -d '{"to": "/ themes / all", "data": {"message": "Это тема сообщения Firebase Cloud Messaging!"}} '
Я получил:
HTTP/2 200
content-type: application/json; charset=UTF-8
date: Tue, 18 Sep 2018 21:38:21 GMT
expires: Tue, 18 Sep 2018 21:38:21 GMT
cache-control: private, max-age=0
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
server: GSE
alt-svc: quic=":443"; ma=2592000; v="44,43,39,35"
accept-ranges: none
vary: Accept-Encoding
{"message_id":5323681878653027379}
Так почему это не работает из firebase
веб-консоль?Может ли это быть проблемой, которая должна быть решена с помощью firebase
?
ОБНОВЛЕНИЕ
Чтобы дополнительно проверить, находится ли это на стороне firebase
Я написал облачную функцию, которая должна отправлять уведомление при обновлении / создании / удалении определенного документа:
exports.sendMessageNotification = functions.firestore().document('conversations/{conversationID}/messages/{messageID}').onWrite((change, context) => {
// Get an object representing the document
// e.g. {'name': 'Marie', 'age': 66}
const newValue = change.after.data();
// ...or the previous value before this update
const previousValue = change.before.data();
// access a particular field as you would any JS property
//const name = newValue.name;
var topic = 'all';
var payload = {
notification: {
title: "You got a new Message",
body: newValue.notification.body,
}
};
admin.messaging().sendToTopic(topic, payload)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
});
Вот мой код, который успешно записывает объект в указанное выше местоположение firestore
:
....
constructor() {
super();
this.onTokenRefreshListener = firebase.messaging().onTokenRefresh(fcmToken => {
// Process your token as required
});
this.messageListener = firebase.messaging().onMessage((message: RemoteMessage) => {
// Process your message as required
alert(message);
});
//this.ref = firebase.firestore().collection('items');
//this.authSubscription = null;
}
....
componentDidMount() {
firebase.messaging().getToken()
.then(fcmToken => {
if (fcmToken) {
console.log(fcmToken);
// Add a new document with a generated id.
const addMessage = firebase.firestore().collection('conversations').doc('1234567').collection('messages').doc('1234567');
data = {
notification: {
title: "You got a new Message",
body: "You got a new message",
}
}
// Set the 'capital' field of the city
const updateMessage = addMessage.update(data).catch((error) => {
alert(error);
addMessage.set(data).catch((error) => {
alert(error);
});
});
} else {
alert("User doesn't have a token yet");
}
}).catch((error) => {
alert(error);
});
....
}
Для вывода я вижу сообщение console.log(fcmToken)
.Когда я проверяю журнал firebase functions
, я вижу Successfully sent message: { messageId: 6994722519047563000 }
.Когда я проверяю firestore
, документ был создан (или обновлен) правильно, и он находится в правильном месте, чтобы быть замеченным (и это на стороне firebase
в соответствии с firebase function logs
) - но я все еще никогда не получаюфактическое уведомление на моем iPhone.
Почему я не получаю сообщение, если оно отправляется?
ОБНОВЛЕНИЕ
Я сейчас получаю уведомления отлогика, которую я создал с помощью firebase functions
, веб-консоль firebase
только кажется, что она не работает - уведомления по-прежнему никогда не отправляются.