Нажмите на уведомление Flutter FCM не вызывает `getInitialMessage()`IOS

Программируем под IOS
Ответить
Anonymous
 Нажмите на уведомление Flutter FCM не вызывает `getInitialMessage()`

Сообщение Anonymous »

Я работал над приложением Flutter, где оно должно поддерживать возможность нажатия на уведомление, и оно переносит вас куда-то в приложение. Однако при нажатии на уведомление оно не вызывает ни один из созданных мной обратных вызовов. Приложение просто открывает обычно домашнюю страницу. Я отправляю уведомления из серверной части Node.js и использую пакет npm firebase-admin для отправки уведомлений.
Я отправляю уведомление следующим образом:

Код: Выделить всё

/**
* 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'
}
}
}
Затем внутри main.dart на стороне клиента я инициализирую фоновый обработчик Firebase, а также устанавливаю обратный вызов getInitialMessage для открытия определенного экрана в приложение при нажатии на уведомление.

Код: Выделить всё

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();
}
Я попробовал установить NotificationHandler.handleNotificationTap() в качестве обратного вызова как для атрибута onDidReceiveNotificationResponse локального плагина уведомлений, так и для FirebaseMessaging.onBackgroundHandler. Ни один из них не вызывается, когда я касаюсь уведомления, полученного на физическом устройстве.
Когда я получаю уведомление от серверной части, выходные данные на стороне приложения выглядят следующим образом:

Код: Выделить всё

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
обратите внимание, что RemoteMessage: null также печатается при получении уведомления, что мне кажется странным.
Наконец, когда я коснитесь уведомления, ничего не напечатается, что наводит меня на мысль, что getInitialMessage вызывается не в нужное время, и

Код: Выделить всё

onMessageOpenedApp
, похоже, вообще не вызывается. У меня также есть оператор печати внутри NotificationHandler.handleNotificationTap(), который никогда не печатается во всем этом процессе, что заставляет меня полагать, что функция никогда не вводится.
В настоящее время выполняется это на iOS. Обязательно включили возможность push-уведомлений и Xcode. Для FirebaseAppDelegateProxyEnabled установлено значение NO.
Почему ни один из этих обратных вызовов не работает, когда я нажимаю на уведомление?

Подробнее здесь: https://stackoverflow.com/questions/791 ... ialmessage
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»