推送通知在 iOS Flutter 上不起作用

问题描述 投票:0回答:1

似乎不知道如何在 iOS 上显示通知,但在 Android 上运行良好。

  • 使用 flutter_local_notification 包
  • 我正在使用物理设备
  • 向 appdelegate.swift 添加了必要的代码

这是我的云函数代码:

// Fetch the first name of the user who created the appointment
const creatorSnapshot = await admin
  .firestore()
  .collection("users")
  .doc(appointment.createdBy)
  .get();
const creator = creatorSnapshot.data();
const creatorName = creator ? creator.first_name : "Someone";
const requestedUserId = appointment.createdBy;

// Get all users to send notification to, excluding the creator
const usersSnapshot = await admin.firestore().collection("users").get();
const tokens = [];
usersSnapshot.forEach((doc) => {
  if (doc.id !== appointment.createdBy) {
    const userToken = doc.data().fcmToken;
    if (userToken) {
      tokens.push(userToken);
    }
  }
});

if (tokens.length === 0) {
  console.log("No valid tokens found. Notification not sent.");
  return null;
}

// Constructing the FCM message
const message = {
  notification: {
    title: "New Session Available",
    body: `${creatorName} has created an appointment for ${appointment.workouts.join(
      ", "
    )} at ${appointment.date_time
      .toDate()
      .toLocaleString()}, are you available?`,
  },
  data: {
    type: "new_appointment",
    appointmentId: appointmentId,
    requestedUserId: requestedUserId,
  },
  tokens: tokens,
};

// Sending the FCM message
return admin
  .messaging()
  .sendMulticast(message)
  .then((response) => {
    console.log(response.successCount + " messages were sent successfully");
  });

这是我处理通知的代码

// iOS Initialization
var initializationSettingsIOS = DarwinInitializationSettings(
  requestAlertPermission: true,
  requestBadgePermission: true,
  requestSoundPermission: true,
  onDidReceiveLocalNotification: onDidReceiveLocalNotification,
);

// request permissions
//for ios
if (Platform.isIOS) {
  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
          IOSFlutterLocalNotificationsPlugin>()
      ?.requestPermissions(
        alert: true,
        badge: true,
        sound: true,
      );
  //for android
} else if (Platform.isAndroid) {
  final AndroidFlutterLocalNotificationsPlugin? androidImplementation =
      flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>();

  // ignore: unused_local_variable
  final bool? grantedNotificationPermission =
      await androidImplementation?.requestNotificationsPermission();
}

// InitializationSettings for both platforms
var initializationSettings = InitializationSettings(
    android: initializationSettingsAndroid, iOS: initializationSettingsIOS);

saveUserTokenToFirestore();
print('step 1');

// initialize the plugins
await flutterLocalNotificationsPlugin.initialize(
  initializationSettings,
  onDidReceiveNotificationResponse:
      (NotificationResponse notificationResponse) {
    if (notificationResponse.notificationResponseType ==
        NotificationResponseType.selectedNotification) {
      selectNotificationSubject.add(notificationResponse.payload);
    }
  },
);

onNotificationTap();

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  print('step 2');
  showNotification(message);
});

FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  onNotificationTap();
});

// Android Notification Details
var androidDetails = const AndroidNotificationDetails(
  'new_appointment',
  'Appointment Notifications',
  channelDescription: 'Get notified about new appointments and updates',
  importance: Importance.max,
);

// iOS Notification Details
var iosDetails = const DarwinNotificationDetails(
    presentAlert: true, presentSound: true, subtitle: 'Notification');

var notificationDetails =
    NotificationDetails(android: androidDetails, iOS: iosDetails);

String payload = json.encode(message.data);

// Display the notification using the flutterLocalNotificationsPlugin
await flutterLocalNotificationsPlugin.show(
  message.hashCode,
  message.notification?.title ?? 'Default Title',
  message.notification?.body ?? 'Default body',
  notificationDetails,
  payload: payload,
);

这是我的信息.plist:

<key>FirebaseAppDelegateProxyEnabled</key> 
<false/>
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>remote-notification</string>
</array>

尝试了网上找到的所有指南,仍然无法收到在 iOS 上工作的通知

ios swift flutter push-notification firebase-cloud-messaging
1个回答
0
投票

你可以尝试像这样编辑你的消息json,添加“apns”:

{
        "message": {
          "token": fcmToken,
          "notification": {
            "title": senderName,
            "body": message,
          },
          "android": {
            "notification": {
              "click_action": "Android Click Action",
            }
          },
          "apns": {
            "payload": {
              "aps": {
                "category": "Message Category",
                "content-available": 1
              }
            }
          }
        }
      }
© www.soinside.com 2019 - 2024. All rights reserved.