0
votes

Last night I was testing Push Notifications from Firebase in my iOS app, and it was working as expected

I was able to send a notification from at Cloud Function to a specific FCM token. This morning notification doesn't arrive when using the same method.

Cloud Function

Here's the function that I use to send the notification:

function sendNotification(title: string, body: string, token: string): Promise<void> {
    const message: admin.messaging.Message = {
        apns: {
            headers: {
                'apns-priority': '10'
            },
            payload: {
                aps: {
                    alert: {
                        title: title,
                        body: body,
                    },
                    sound: "default"
                }
            }
        },
        token: token
    }
    return admin.messaging().send(message).then(response => { console.log(`Notification response ${response}`) }).then(justVoid)
}

Here token is the token I received from the InstanceId in the iOS app. When this function is triggered, I see the following in Firebase web console's Cloud Function log:

Notification response projects/project-name/messages/0:1571998931167276%0f7d46fcf9fd7ecd

Which, as far as I understand, is a success message. So I'm expecting the notification to show up on the device at this point, but nothing.

iOS App

I've followed this guide to troubleshoot, and am sure that the setup is right: https://firebase.google.com/docs/cloud-messaging/ios/first-message?authuser=0

I did try to re-install the app on the device on which Im testing: I've verified that the app does through these step after re-install:

  • call: UNUserNotificationCenter.current().requestAuthorization(options:, completionHandler:)

  • call: UIApplication.shared.registerForRemoteNotifications()

  • listen to updated FCM token by implementing: func messaging(_ messaging:, didReceiveRegistrationToken fcmToken:)

  • call: InstanceID.instanceID().instanceID(handler:)

  • double check that notifications is allowed for my application in the iOS settings app.

Test Notification from console

I've tried sending a Test Notification in from Notification Composer, using a the recent FCM token for the test device, but this notification doesn't show up either, and it doesn't give me any feedback on screen whether the notification is successfully sendt or not.

What am I doing wrong here?

Any Suggestions to how I can debug this issue?

1

1 Answers

0
votes

When we are working with Push Notification then it is very harder to debug issue.

As per my experience, there is nothing wrong with your typescript or iOS code because earlier it was worked perfectly. Below is the possible reason if the push notification is not working.

Generally, the APNS related issue occurs due to the certificate.

  • Make sure you are uploading the correct APNS profile to the firebase console for both development and release mode.

  • Make sure you have enabled the notification in capabilities.

    Your Project -> capabilities -> turn on Push Notifications

  • Make sure you're added correct GoogleService-Info.plist to the
    project.

  • APNS Certificate is not expired.

  • Make sure you're using the latest version of the firebase.

  • Your device time should be automatic, not feature time.

If you still think it is code related issue and the above solution is not working then you can go with the below wrapper class of HSAPNSHelper class which is created by me and it is working for iOS 10 and later .

import Foundation
import UserNotifications
import Firebase

class HSAPNSHelper: NSObject {

    static let shared = HSAPNSHelper()
    let local_fcm_token = "local_fcm_token"

    var notificationID = ""

    func registerForPushNotification(application:UIApplication){

        FirebaseApp.configure()

        self.getFCMToken()
        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound]) { (granted, error) in
            DispatchQueue.main.async {
                self.getFCMToken()
            }
        }
        application.registerForRemoteNotifications()
    }
}


extension HSAPNSHelper:UNUserNotificationCenterDelegate {

    fileprivate func getFCMToken() {
        InstanceID.instanceID().instanceID(handler: { (result, error) in
            if error == nil, let fcmToken = result?.token{
                print("FCM Token HS: \(fcmToken)")
                UserDefaults.standard.set(fcmToken, forKey: self.local_fcm_token)
            }
        })
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("didFailToRegisterForRemoteNotificationsWithError : \(error)")
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

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

    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        let userInfo = notification.request.content.userInfo as! [String: Any]
        print(userInfo)
        completionHandler([.alert, .badge, .sound])
    }

    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        print(userInfo)
        self.notificationRedirection()
    }

    private func notificationRedirection(){

    }

    func fcmToken() -> String{
        return UserDefaults.standard.string(forKey:local_fcm_token) ?? ""
    }
}

How to use?

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        //For Push notification implementation
        HSAPNSHelper.shared.registerForPushNotification(application: application)
        return true
    }

Use fcmToken() to get current FCM token.