Я отправляю уведомление следующим образом:
Код: Выделить всё
/**
* Trigger sending a notification
*/
const sendNotification = async ({
title,
body,
data,
notificationType,
topic,
sendTo,
mediaUrl,
}) => {
let tokens = [];
if (sendTo) {
console.log(`sending targeted notitification to: ${sendTo}`);
tokens = await getUserFCMTokens(sendTo);
}
const notification = {
data: {
...data,
notificationType: NOTIFICATION_TYPE[notificationType].toString(),
title: title,
body: body,
},
...(topic && { topic: topic }),
...(tokens.length > 0 && { tokens }),
apns: {
headers: {
'apns-priority': '5',
},
payload: {
aps: {
contentAvailable: true,
},
},
},
android: {
priority: 'high',
notification: {
click_action: 'FLUTTER_NOTIFICATION_CLICK',
priority: 'high',
sound: 'default',
},
},
};
console.log(notification);
try {
if (tokens.length > 0) {
// Send to multiple devices
const response = await admin
.messaging()
.sendEachForMulticast(notification);
console.log(
`Successfully sent message to ${response.successCount} devices`
);
if (response.failureCount > 0) {
console.log(
`Failed to send message to ${response.failureCount} devices`
);
response.responses.forEach((resp, idx) => {
if (!resp.success) {
console.log(
`Failed to send to token at index ${idx}: ${resp.error}`
);
}
});
}
} else if (topic) {
// Send to topic
const response = await admin.messaging().send(notification);
console.log('Successfully sent message:', response);
} else {
console.log('No valid recipients (tokens or topic) specified');
}
} catch (error) {
console.error('Error sending notification:', error);
}
};
Код: Выделить всё
{
data: {
group: '6716a89768497667e665546c',
media: '',
message: '6716a8d868497667e66554a4',
notificationType: '3',
title: 'title goes here',
body: '@zh22: Message goes here '
},
topic: 'group_6716a89768497667e665546c',
apns: { headers: { 'apns-priority': '5' }, payload: { aps: [Object] } },
android: {
priority: 'high',
notification: {
click_action: 'FLUTTER_NOTIFICATION_CLICK',
priority: 'high',
sound: 'default'
}
}
}
Код: Выделить всё
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
await AppData.initiate();
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print("onMessage: $message");
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print("onMessageOpenedApp: $message");
NotificationHandler.handleNotificationOnTap(message);
});
FirebaseMessaging.onBackgroundMessage(_onBackgroundMessage);
FirebaseMessaging.instance
.getInitialMessage()
.then(NotificationHandler.handleNotificationOnTap);
runApp(
ShowCaseWidget(builder: (context) {
return const MyApp();
}),
);
}
@pragma("vm:entry-point")
Future _onBackgroundMessage(RemoteMessage message) async {
print("onBackgroundMessage: $message");
print("data: ${message.data}");
final NotificationRepository notificationRepository =
NotificationRepositoryImpl();
final FlutterLocalNotificationsPlugin localNotificationsPlugin =
FlutterLocalNotificationsPlugin();
// show notification
const AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(
"basecamp_notifications", "Basecamp Notifications",
importance: Importance.max,
priority: Priority.high,
ticker: 'ticker');
const DarwinNotificationDetails iosNotificationDetails =
DarwinNotificationDetails(
presentAlert: true,
presentSound: true,
interruptionLevel: InterruptionLevel.active);
int notificationId = 1;
const NotificationDetails platformSpecifics = NotificationDetails(
android: androidNotificationDetails, iOS: iosNotificationDetails);
await localNotificationsPlugin.initialize(
const InitializationSettings(
android: AndroidInitializationSettings("@mipmap/ic_launcher"),
iOS: DarwinInitializationSettings(),
),
onDidReceiveNotificationResponse: (NotificationResponse details) {
if (details.payload != null) {
final data = json.decode(details.payload!);
final message = RemoteMessage(data: Map.from(data));
NotificationHandler.handleNotificationOnTap(message);
}
},
);
final title = message.data["title"];
final body = message.data["body"];
await localNotificationsPlugin.show(
notificationId, title, body, platformSpecifics,
payload: message.data.toString());
}
@pragma('vm:entry-point')
void notificationTapBackground(NotificationResponse notificationResponse) {
print(notificationResponse);
// NotificationHandler.handleNotificationOnTap();
}
Когда я получаю уведомление от серверной части, выходные данные на стороне приложения выглядят следующим образом:
Код: Выделить всё
flutter: onBackgroundMessage: Instance of 'RemoteMessage'
flutter: data: {body: @zh22: Message goes here, message: 6716a8d868497667e66554a4, title: @title goes here, group: 6716a89768497667e665546c, notificationType: 3, media: }
flutter: remoteMessage: null
Наконец, когда я коснитесь уведомления, ничего не напечатается, что наводит меня на мысль, что getInitialMessage вызывается не в нужное время, и
Код: Выделить всё
onMessageOpenedAppВ настоящее время выполняется это на iOS. Обязательно включили возможность push-уведомлений и Xcode. Для FirebaseAppDelegateProxyEnabled установлено значение NO.
Почему ни один из этих обратных вызовов не работает, когда я нажимаю на уведомление?
Подробнее здесь: https://stackoverflow.com/questions/791 ... ialmessage
Мобильная версия