From cfc1fd0a8efefb69f07cbb96aa40706e5adafeb7 Mon Sep 17 00:00:00 2001 From: Hamza-Ayed Date: Mon, 18 May 2026 18:07:36 +0300 Subject: [PATCH] fix: resolve iOS APNS token waiting loop in FirebaseService to guarantee successful FCM registration --- .../lib/services/firebase_service.dart | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/whatsapp_app/lib/services/firebase_service.dart b/whatsapp_app/lib/services/firebase_service.dart index 45ae77a..98708da 100644 --- a/whatsapp_app/lib/services/firebase_service.dart +++ b/whatsapp_app/lib/services/firebase_service.dart @@ -1,5 +1,6 @@ import 'dart:async'; import 'dart:convert'; +import 'dart:io'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:get/get.dart'; @@ -76,9 +77,27 @@ class FirebaseService extends GetxService { void _setupFcmTokenRegistration() async { try { + // For iOS, wait until the APNS token is successfully initialized by the OS before calling getToken() + if (Platform.isIOS) { + String? apnsToken = await _messaging.getAPNSToken(); + int retries = 0; + while (apnsToken == null && retries < 15) { + print('[FCM] APNS token not set yet. Waiting 1 second... (Attempt ${retries + 1}/15)'); + await Future.delayed(const Duration(seconds: 1)); + apnsToken = await _messaging.getAPNSToken(); + retries++; + } + if (apnsToken != null) { + print('[FCM] APNS Token successfully obtained: $apnsToken'); + } else { + print('[FCM WARNING] Failed to obtain APNS token after 15 attempts. FCM registration might fail.'); + } + } + final token = await _messaging.getToken(); if (token != null) { - print('[FCM] Token obtained: ${token.substring(0, 15)}...'); + final displayToken = token.length > 15 ? token.substring(0, 15) : token; + print('[FCM] Token obtained: $displayToken...'); _registerTokenOnServer(token); } } catch (e) {