'iOS Application does not receive data message send by FCM payload

I am trying to send data message from fcm payload by using Laravel framework as shown below.

$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60*20)
              ->setContentAvailable(true)
              ->setCollapseKey('collapse_all');

$option = $optionBuilder->build();

$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData([
  'name'=> 'pushDataUpdate',
  'time'=> $message['time'],
  'location'=> $message['location'],
  'queue'=> $message['queue']
]);

$data = $dataBuilder->build();

$token = $fcm_token;
$downstreamResponse = FCM::sendTo($token, $option, null, $data);
                                
$dataSent = array(
  "title" => 'Update Data',
  "fcm_success" => $downstreamResponse->numberSuccess(),
  "fcm_failure" => $downstreamResponse->numberFailure(),
  "fcm_modification" => $downstreamResponse->numberModification(),
  "token_to_delete" => $downstreamResponse->tokensToDelete(),
  "token_to_modify" => $downstreamResponse->tokensToModify(),
  "token_to_retry" => $downstreamResponse->tokensToRetry(),
  "token_to_error" => $downstreamResponse->tokensWithError()
);

Payload Data Response pass back in Android.

Message data payload: {name=pushDataUpdate,  time=10/3/2022, location=End, queue=End}
Message data payload size more than 0

When I try to call this data message in iOS app it does not come back but it does come back in Android app. I saw that many online answer says that it will call didReceiveRemoteNotification func when coming back. However, my case is the data message did not pass back when I open the app, close the app or kill the app.

Below are my App Delegate code for the app

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
      do {
          sleep(1)
      }
    
      FirebaseApp.configure()

      if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        Messaging.messaging().delegate = self

        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
          options: authOptions,
          completionHandler: {_, _ in })
      } else {
        let settings: UIUserNotificationSettings =
        UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
      }

      application.registerForRemoteNotifications()
      NotificationCenter.default.addObserver(self, selector: #selector(removeBadgeNumber), name: UIApplication.willEnterForegroundNotification, object: nil)
      Messaging.messaging().delegate = self
      UIApplication.shared.applicationIconBadgeNumber = 0
    
      return true
  }

  @objc func removeBadgeNumber() {
      UIApplication.shared.applicationIconBadgeNumber = 0
      print("badge: \(UIApplication.shared.applicationIconBadgeNumber)")
  }

  func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
    return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
  }

  func application(_ application: UIApplication, didDiscardSceneSessions : Set<UISceneSession>) {
    
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
      print("Notification click opened")
      let pushNotification = PushNotification()
      let userInfo = response.notification.request.content.userInfo
      let title = userInfo["title"] as! String
      pushNotification.navigate(with: title)
      print(userInfo)
      completionHandler()
}

  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
      print("Foreground notification")
      completionHandler([.alert,.badge,.sound])
}

  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    var token = ""

    for i in 0..<deviceToken.count {
      token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
    }

    print("Registration succeeded!")
    print("Token: ", token)
   }

  func application(_ application: UIApplication,
                 didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult)
                   -> Void) {
    
      if let name = userInfo["name"]{
        
          if(name as? String == "pushDataUpdate"){
              var info = [String: Any]()
            
              info["location"] = userInfo["location"]
              info["time"] = userInfo["time"]
              info["queue"] = Int(userInfo["queue"] as! String)
            
              NotificationCenter.default.post(name: Notification.Name(rawValue: DATA_NOTIFICATION), object: nil, userInfo: info)
          }
      }
    completionHandler(UIBackgroundFetchResult.newData)
  }
}



extension AppDelegate{
  func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
    
      print("Firebase registration token: \(fcmToken)")
    
      let dataDict:[String: String] = ["token": fcmToken ?? ""]
      NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
    
  }
}

May I know which steps that I code it wrong?

I can get the notification pass back from firebase but not the data message.

I am struggle at this part for days, hope anyone could help me with this.

Thank you in advanced!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source