-1

I am having trouble with getting push notification, here's my payload

{
  "to": "erOZW7CN....(fcm token)",
  "data": {
    "body": "Incoming-Call",
    "title": "AppName",
    "type": "incoming-call",
    "number": "0212222222"
  },
  "aps": {
    "alert": {
      "title": "AppName",
      "body": "Incoming-Call"
    }
  }
}

The data part is for Android. When I use notification instead of aps it works but the Android side gets buggy. So I need to use aps to detect request. I've done lots of research but couldn't find any solution.

Here's my AppDelegate

import UIKit
import CoreData
import Firebase
import Network


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        FirebaseApp.configure()
        
        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()
        Messaging.messaging().delegate = self
        
        return true
    }
    

    
    // MARK: UISceneSession Lifecycle

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

    @available(iOS 13.0, *)
    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {

    }
    
    lazy var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "Database")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()
    
    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
    }
    

    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)
        UserDefaults.standard.set(fcmToken, forKey: "fcmToken")
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("Push Received: \(userInfo)")
        //TODO: CALLKIT DETECT
    }
}

Note: I am sending request from Postman

Would be great to find a solution here. Thanks.

MilanPanchal
  • 2,943
  • 1
  • 19
  • 37
Oğuz
  • 3
  • 4
  • Maybe this could be helpful https://stackoverflow.com/questions/37358462/firebase-onmessagereceived-not-called-when-app-in-background – Haris Sep 11 '20 at 07:11
  • What do you mean by "not able"? – Roman Ryzhiy Sep 11 '20 at 07:12
  • @HarisD. this is for android. – Oğuz Sep 11 '20 at 07:13
  • Ok. I think you can try to debug using https://github.com/KnuffApp/Knuff. Maybe will give you some extra information. Could be that: - your token is generated for a prod but you are trying to send PN to sandbox APN and vice versa. - Could be a problem with certificates. – Haris Sep 11 '20 at 07:22
  • @HarisD. knuff sending to device token, i need to send notification fcm token and detect it with "aps" token – Oğuz Sep 11 '20 at 07:32
  • Are you testing the notifications on a simulator or on a device? – Andrew Sep 11 '20 at 07:37
  • @Andrew real device – Oğuz Sep 11 '20 at 07:40
  • Have you tried sending the notification from the Firebase console rather than from Postman? – Andrew Sep 11 '20 at 07:41
  • @Andrew it works on firebase console but it doesnt work with payload above. bcs i am using "aps" instead of "notification" – Oğuz Sep 11 '20 at 07:45

1 Answers1

0

Generate your payload as following when sending Push Notification via FCM or APNS.

Basic Payload: iOS and Android (Sending via FCM)

{
  "message": {
      "notification": {
        "body": "YOUR MESSAGE BODY HERE",
        "title": "YOUR MESSAGE TITLE HERE"
      }
  }
}

Basic Payload: iOS (Sending via APNS)

{
  "aps": {
    "alert": {
      "body": "YOUR MESSAGE BODY HERE",
      "title": "YOUR MESSAGE TITLE HERE"
    }
  }
}

NOTE:

In the didReceiveRemoteNotification function you will receive your payload as per iOS style.

MilanPanchal
  • 2,943
  • 1
  • 19
  • 37
  • "data" part is for android, when i use "notification" instead of "aps" it works but android side gets buggy, so i need to use "aps" to detect request – Oğuz Sep 11 '20 at 10:34
  • @Oğuz It really looks like you are confusing two different systems. MilanPanchal has shown the correct way for setting up notifications. I think you should take some time and read the documentation on how push notifications work from [FCM](https://firebase.google.com/docs/cloud-messaging/concept-options) and from [Apple](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html#//apple_ref/doc/uid/TP40008194-CH11-SW1). In FCM `Data` is **not** just for Android it is for sending a payload that is consumed by the app. – Andrew Sep 11 '20 at 12:06