In my App, i'm facing an issue with push-notification
. Firebase-Notification
configuration is done perfectly. And working test notification which are sent from Firebase-console. Now I'm facing the issue, when the notification is fired from backend side and notification is not getting received in any of my iOS Device, where the App is fresh installed.
After terminating App if i do Logged-Out and then Re-login, then it is working fine from backend side.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
fcmTokenString = Messaging.messaging().fcmToken ?? ""
print("deviceTokenString \(deviceTokenString)")
print("fcmToken \(Messaging.messaging().fcmToken ?? "")")
UIViewController().deviceToken = deviceTokenString //This will stored in UserDefault
UIViewController().fcmToken = fcmTokenString //This will stored in UserDefault
}
Laravel
Backend Code$url = 'https://fcm.googleapis.com/fcm/send';
$FcmToken = User::whereNotNull('fcm_token')->pluck('fcm_token')->all();
// echo "<pre>"; print_r($FcmToken); die;
// $sendusersids = User::whereIn('id', $users_ids)->whereNotNull('fcm_token')->pluck('id')->all();
foreach ($FcmToken as $key => $FcmTokenone) {
$fcmService = new FCMService();
// dd($fcmService);
// $deviceToken = 'eAzUspsvcEvIjjZ0NVuwBp:APA91bHLgRtV-Oa3xl3HbalmZuhbaslU_IO8HnPi15OL8AabK6aSPF-lo7AC1GcA4BL_YW1osBpMXvuc4nXWtOySqjDQDp1tpGcyzwc8QoTd5Ay3_iayoAw'; // Token for the device you want to notify
// $deviceToken = 'fbb-W4NZQni5DUkk6fgnPy:APA91bGBUCFueEuUZnad-0jKWusKQoygeQtrvGz6BwfSgBv6RLfJh3U-beEXeIp_S36j4xc5NOsFIexSG4xiM4i3iKBGMb3qnbg-NPB6VgjWfuwM6XnAtW8'; // peterson fcm token
$title = 'GLO Mini Golf Promo code';
$body = $data['description'];
$data1 = [
// "registration_ids" => [$deviceToken],
// "registration_ids" => [$FcmTokenone[0]],
"registration_ids" => [$FcmTokenone],
"notification" => [
"title" => $title,
"body" => $body,
],
"data" => [
"type" => 'group',
"id" => 123,
]
];
$response = $fcmService->sendNotification($data1);
Log::error("pushnotificaiotn-->".$response);
$this->client = new Client();
$this->serverKey = env('FIREBASE_SERVER_KEY'); // Server key from Firebase credentials
$this->projectId = env('FIREBASE_PROJECT_ID'); // Firebase project ID
public function sendNotification($notification_data)
{
$access_token = self::getAccessToken();
$device_token = $notification_data['registration_ids'][0];
$title = $notification_data['notification']['title'];
$body = $notification_data['notification']['body'];
$type = $notification_data['data']['type'];
$id = $notification_data['data']['id'];
$message = array(
'token' => $device_token,
'notification' => [
"title" => $title,
"body" => $body,
],
'data' => [
"type" => (string)$type,
"id" => (string)$id
],
);
Log::error("notification_message--->".json_encode($message));
$arrayToSend = array('message' => $message);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://fcm.googleapis.com/v1/projects/".$this->projectId."/messages:send",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($arrayToSend),
CURLOPT_HTTPHEADER => array(
"authorization: Bearer ".$access_token,
"cache-control: no-cache",
"content-type: application/json"
),
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
Log::error("notification_res-->".$response);
if ($response === false) {
$error = curl_error($curl);
Log::error("sendNotification error".$error);
curl_close($curl);
}
curl_close($curl);
Log::error("sendNotification success ".$response);
$responseData = json_decode($response, true);
return true;
}
Notification
Delivery status log[2025-01-23 12:26:40] production.ERROR: pushnotificaiotn-->1
[2025-01-23 12:26:40] production.INFO: Access Token Generated Successfully: {"access_token":"ya29.c.c0ASRK0GbNRMdPbCklv1jZ1uBkgD-Y5an_0WW3GIXYQisl3daLuFO4i0_fxAdpVu8RxKCNSJZ-HUQJFu1au3C618-NkZsB0yd8OdO_-wLVXwyrPJ782c-uPhkhvOI4DceC7qvBfQjo7SIb9I6BQ2C06ZSpnBrNJvhGL_dly6t4ufYCwknPawDuGRyHD5pOb_jVsaxEqAs5ZxEMJEPMoGnZowWMHxosKtwHB-ofno_P6TYQUMYL9iKF4nr8H6XYjrGX8EQl0JrduwpS4hXn_rCCY05y4zdTO_GGAb_Dii88qhxGmwLo0MJfuMnHUJrrGBtd2UPys6K5DPcsFs9Bhb2N8w1u2PT7XAIk1NFsLYSiyZ7B2ozySW8B30NmE385AZ0UmIuy-k_psZrjcR1zYh0IFyFBy3Va3_nfUStWI0Ou9Q-8knZiMVUyhjM787tcyFavFO5hUV9ux4appgi45kwua-t8S1uOJjrlj1R23lpU8IeXaOmdoug6o2c1hbIM94aO_cnh7VcWszMp7OYn3Qvb72jhr0IV1M0RQwy2hvb67zJuIVyRk1e2Fh-Wj3yQfmer02YyRxj7rSXJo2Q2MIioQYVfO6ym4ixczddkuvYliocptSrYdcskyQYV6Jv7ZW2tw8wMI0nJ9v0gSJdktpwYr219Mmwt1pwp6WZ37tpJYQkUB9mrO2furu0Vqyam59M-nfloxMeInhOo9-8a80poFrQupYIk665ntwWBdVs4td0JQWF1FVnvsQqM9Z7emsF075ecag9xXJ2is3Q_M58OdgzFjqioXVI5aBZvd-x81nsJz7zMp3Za0B0kZYIsbl7-xdtt-OweQsntoh65oa_O-Xnhpfpku8xidZ5V642foF9rvzj16hQxxk4V2aO1Qpj5g1eYt2j_g_kJtgBYWoOjaIIewXspg_goIMz4xz28jcMV88cv_I3-w9bj0w705vtxyiSrORp7ZpUyOfWiFqja4tVtjV4Qmzy3zv5tWxpRz6Op2xljnI8VyX9","expires_in":3599,"token_type":"Bearer","created":1737635200}
[2025-01-23 12:26:40] production.ERROR: notification_message--->{"token":"csQwYhf3FUnvuyLVhHCFEq:APA91bFIMKRtNOaRC0p_-Hgl6bgSg7C-lEQ7uBSUHBivNIH5lra8hnl92ZSm9lcfk9N4gpCwwP8w26s3iX0d121ehEr2S7-S7zbSBFgYNUOZaEDDszOUEtL_uHzIgbOykb85Au_zUcED","notification":{"title":"GLO Mini Golf Promo code","body":"test"},"data":{"type":"group","id":"123"}}
[2025-01-23 12:26:41] production.ERROR: notification_res-->{ "name": "projects/glo-mini-golf-1dac4/messages/1737635200881686" }[2025-01-23 12:26:41] production.ERROR: sendNotification success { "name": "projects/glo-mini-golf-1dac4/messages/1737635200881686" }
After go through many articles and similar questions from StackOverflow, I've get that the root cause of issue was FCM token
, so I've changed the method for token fetching. And Issue has been resolved, by confirming FIRMessagingDelegate
to AppDelegate
.
e.g.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Messaging.messaging().delegate = self
}
And updated code for FCM Token fetching. Before it was getting through didRegisterForRemoteNotificationsWithDeviceToken
, and updated to didReceiveRegistrationToken
of FIRMessaging
.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
//fcmTokenString = Messaging.messaging().fcmToken ?? "" //Commented
print("deviceTokenString \(deviceTokenString)")
print("fcmToken \(Messaging.messaging().fcmToken ?? "")")
UIViewController().deviceToken = deviceTokenString
}
FIRMessaging
instead of default AppDelegate
methods.func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
guard let token = fcmToken else { return }
print("Firebase registration token: \(token)")
if let refreshedToken = fcmToken {
fcmTokenString = fcmToken ?? ""
UIViewController().fcmToken = fcmToken ?? fcmTokenString
}
}