我目前正在尝试编写聊天应用。我已经完成了使用Firebase聊天的基本功能。现在,当数据库中有新消息时,我想向用户推送通知。 我现在使用下面显示的代码设置了云功能。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPushNotification = functions.database.ref('/message').onWrite(event => {
const payload = {
notification: {
title: 'message!',
body: 'new message',
badge: '1',
sound: 'default',
}
};
return admin.database().ref('fcmToken').once('value').then(allToken =>
{
if (allToken.val())
{
const token = Object.keys(allToken.val());
return admin.messaging().sendToDevice(token, payload).then(response =>{
return null;
});
}
return null;
});
});
通过查看日志,此代码似乎可以正常工作。我通过在真实设备中运行应用程序来测试了该功能,但是它不起作用。 有线的事情是我可以使用云消息传递将通知发送到设备,并且可以正常工作。但是我不知道为什么这行不通。有人可以帮我吗?
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[FIRApp configure];
[GIDSignIn sharedInstance].clientID = [FIRApp defaultApp].options.clientID;
[GIDSignIn sharedInstance].delegate = self;
//notifications:
[FIRMessaging messaging].delegate = self;
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:authOptions
completionHandler:^(BOOL granted, NSError * _Nullable error) {
// ...
}];
[application registerForRemoteNotifications];
return YES;
}