swift – Push notification not working on iOS Flutter


here is my code for the cloud function:

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");
  });```

And here is my code for handling the notifications

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,
);

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img