1

I am getting Push Notifications, when my app is in background mode but the notification is not showing when the app is in foreground mode.

I searched a lot about this issue and they say, you have to implement

willPresent notification: UNNotification

function but I already have this function. Below is my App Delegate's code:

class AppDelegate: NSObject, UIApplicationDelegate {
    
    let gcmMessageIDKey = "gcm.message_id"
    
  func application(_ application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    
      FirebaseApp.configure()
      IQKeyboardManager.shared.enable = true
      /// code for push notifications
      Messaging.messaging().delegate = self
      
      if #available(iOS 10.0, *) {
          // For iOS 10 display notification (sent via APNS)
          UNUserNotificationCenter.current().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()
      
      
      return true
  }
    /// code for notifications
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                        fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

         if let messageID = userInfo[gcmMessageIDKey] {
             Helper.shared.printDebug("Message ID: \(messageID)")
         }

        Helper.shared.printDebug(userInfo)

        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            
            if userInfo["other_data"] as? String == "Request Notification" {
                
                
                NotificationCenter.default.post(name: Notification.Name("request_notification"), object: nil, userInfo: userInfo)
            } else {
                NotificationCenter.default.post(name: Notification.Name("message_notification"), object: nil, userInfo: userInfo)
            }
        }
        
         completionHandler(UIBackgroundFetchResult.newData)
       }
}
/// code for push notifications
extension AppDelegate: MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {

      let deviceToken:[String: String] = ["token": fcmToken ?? ""]
        Helper.shared.printDebug("Device token: \(deviceToken)") // This token can be used for testing notifications on 
        
        UserDefaults.standard.set(fcmToken, forKey: UserDefaultEnum.deviceId.rawValue)
    }
}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    if let messageID = userInfo[gcmMessageIDKey] {
        Helper.shared.printDebug("Message ID: \(messageID)")
    }

      Helper.shared.printDebug(userInfo)

    // Change this to your preferred presentation option
    completionHandler([[.banner, .badge, .sound]])
  }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Helper.shared.printDebug(deviceToken)
        
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        Helper.shared.printDebug(error.localizedDescription)
    }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo

      if let messageID = userInfo[gcmMessageIDKey] {
          Helper.shared.printDebug("Message ID from userNotificationCenter didReceive: \(messageID)")
      }
      Helper.shared.printDebug(userInfo)
      
      DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
          
          if userInfo["other_data"] as? String == "Request Notification" {
              
              NotificationCenter.default.post(name: Notification.Name("request_notification"), object: nil, userInfo: userInfo)
          } else {
              NotificationCenter.default.post(name: Notification.Name("message_notification"), object: nil, userInfo: userInfo)
          }
      }
      
      completionHandler()
  }
}

App's notification's settings are:

settings image

Can someone help me out with this issue?

I am using xCode 14.3 and iOS 16.5

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.