fix: resolve iOS APNS token waiting loop in FirebaseService to guarantee successful FCM registration

This commit is contained in:
Hamza-Ayed
2026-05-18 18:07:36 +03:00
parent 60139d98c5
commit cfc1fd0a8e

View File

@@ -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) {