Notification Push n'envoyant pas de FCM après modification du certificat APNs

Je n'avais aucun problème à envoyer des notifications push de FCM à mon application iOS avant l'expiration d'un de mes certificats. Après l'avoir modifié, la FCM ne transmet plus de messages. J'ai lu cet article (https://firebase.googleblog.com/2017/01/debugging-firebase-cloud-messaging-on.html) et voici les étapes de validation que j'ai traversé jusqu'à présent, mais je me bats la tête contre le mur maintenant...

  • Commentée tout connectToFCM fonctions
  • Pusher téléchargé et peut envoyer avec succès des notifications à l'appareil en utilisant L'APNS cert
  • succès des appels à la FCM (réponse ci-dessous))
    • {"multicast_id":7774794018682407760,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1493321644068397%b76e8527b76e8527"}]}
  • essayé de recréer à la fois des certs de développement et de production
  • essayé de les exporter à partir de porte-clés avec et sans mot de passe

Quelqu'un a de l'expérience avec cette chose super frustrante, et a des conseils sur la façon de procéder?

il est également intéressant de noter que je ne suis pas en mesure de supprimer les certs APNs, je vois l'option, mais il est grisé et je ne peux pas le sélectionner.

16
demandé sur AL. 2017-04-27 22:43:07

3 réponses

Ceci est utile pour comprendre le flux.

enter image description here

image courtoisie de Le Firebase Blog

Vous avez testé que L'APN envoie à l'application. De sorte que le certificat est bien.

le blog vous avez lié, obtenir une réponse réussie en faisant un appel curl signifie seulement que le message est reçu par la FCM. Cela ne signifie pas que le message est fait à la APNs.

envoyer un message directement en utilisant le panneau de notification Firebase, pour voir si la FCM communique avec les APN.

si cela fonctionne, il y a un problème avec le format de votre message.

Si ça ne fonctionne pas.

:

  1. la priorité du message est définie à high, donc ils sont envoyés immédiatement.

  2. "content_avitable": true

  3. désinstaller et réinstaller l'application

  4. vérifiez le code de votre serveur.

2
répondu Yvette Colomb 2017-09-11 16:54:11

au lieu d'utiliser les certificats APNS pour la notification push, vous pouvez créer une clé APNs et l'utiliser pour toutes les applications.

APNs Utilisez le service de notification Apple Push pour vos demandes de notification. Une clé est utilisée pour toutes vos applications. Pour de plus amples renseignements, veuillez consulter le guide de programmation des avis locaux et à distance.

même la FCM soutient ceci. maintenant, vous pouvez éviter le casse-tête de créer un certificat APNS pour chaque ID D'application.

1
répondu KavyaKavita 2017-09-11 03:37:44

veuillez mettre à jour vos certificats APNs (Production et développement) dans Votreprojetsetting= > cloudmessaging=> configuration de l'application iOS. Firebase Cloud Messaging peut utiliser une clé d'authentification APNs ou un certificat APNs pour se connecter avec APNs

Remarque: confirmez vos justificatifs D'identité (SenderID , clé de serveur Legacy, clé de serveur).

requête HTTP POST: pour l'envoi de notifications.

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u......7Udno5aA
{
    "registration_ids": ["regId1","regId2"],
    "data": {
        "title": "App Name",
        "message": "Hello this is for testing",
        "body": "Hello this is for testing"

    },
    "content-available": true,
    "priority": "high",
    "notification": {
        "title": "App Name",
        "message": "Hello this is for testing",
        "body": "Hello this is for testing"
    }
}

Ajouter le code suivant dans votre AppDelegate.swift

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            self.fcmInitialSetup(application)
            return true
        }
        func fcmInitialSetup(_ application: UIApplication){

            // [START register_for_notifications]
            if #available(iOS 10.0, *) {
                let uns: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
                application.registerUserNotificationSettings(uns)
                application.registerForRemoteNotifications()

            } else {
                let settings: UIUserNotificationSettings =
                    UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
                application.registerUserNotificationSettings(settings)
            }

            application.registerForRemoteNotifications()

            // [END register_for_notifications]

            FIRApp.configure()

            // Add observer for InstanceID token refresh callback.
            NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)

            if let token = FIRInstanceID.instanceID().token() {
                sendTokenToServer(token)
            }
        }

        func sendTokenToServer(_ currentToken: String) {
            print("sendTokenToServer() Token: \(currentToken)")
            // Send token to server ONLY IF NECESSARY

            print("InstanceID token: \(currentToken)")
            self.token = currentToken
            UserDefaults.standard.set(self.token, forKey: "token")
            UserDefaults.standard.synchronize()
            if self.token != nil{
                let userInfo = ["token": self.token]
                NotificationCenter.default.post(
                    name: Notification.Name(rawValue: self.rkey), object: nil, userInfo: userInfo)
            }
        }


        // NOTE: Need to use this when swizzling is disabled
        func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
            let tokenChars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
            var tokenString = ""

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

            FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)
            print("Device Token:", tokenString)
            print("FIRInstanceID.instanceID().token() Token:", FIRInstanceID.instanceID().token())
            if let tokenData = FIRInstanceID.instanceID().token(){
                UserDefaults.standard.set(tokenData, forKey: "token")
                UserDefaults.standard.synchronize()
                let userInfo = ["token": tokenData]
            }
        }

        func tokenRefreshNotification(_ notification: Notification) {
            // NOTE: It can be nil here
            //        print("Token:\(FIRInstanceID.instanceID().token()!)")
            if let refreshedToken = FIRInstanceID.instanceID().token() {
                print("InstanceID token: \(refreshedToken)")
                UserDefaults.standard.set(refreshedToken, forKey: "token")
                UserDefaults.standard.synchronize()
                print("update now \(self.token)")
                if self.token != nil{
                    let userInfo = ["token": self.token]
                    NotificationCenter.default.post(
                        name: Notification.Name(rawValue: self.rkey), object: nil, userInfo: userInfo)
                }

            }

            // Connect to FCM since connection may have failed when attempted before having a token.
            connectToFcm()
        }
        // [END refresh_token]
        func connectToFcm() {
            FIRMessaging.messaging().connect { (error) in
                if (error != nil) {
                    print("Unable to connect with FCM. \(error)")
                } else {
                    print("Connected to FCM.")
                }
            }
        }

        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
            print(userInfo)
        }

        func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
            print("Within open URL")
            return true
        }


        // [START receive_apns_token_error]
        func application( _ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError
            error: Error ) {
            print("Registration for remote notification failed with error: \(error.localizedDescription)")
            // [END receive_apns_token_error]
            let userInfo = ["error": error.localizedDescription]
            NotificationCenter.default.post(
                name: Notification.Name(rawValue: rkey), object: nil, userInfo: userInfo)
        }

        func registrationHandler(_ token: String!, error: NSError!) {
            if (token != nil) {
                self.token = token!
                print("Registration Token: \(self.token)")
                UserDefaults.standard.set(self.token, forKey: "token")
                UserDefaults.standard.synchronize()
                let userInfo = ["token": self.token]
                NotificationCenter.default.post(
                    name: Notification.Name(rawValue: self.rkey), object: nil, userInfo: userInfo)
            } else {
                print("Registration to GCM failed with error: \(error.localizedDescription)")
                let userInfo = ["error": error.localizedDescription]
                NotificationCenter.default.post(
                    name: Notification.Name(rawValue: self.rkey), object: nil, userInfo: userInfo)
            }
        }

        func registerForPushNotifications(_ application: UIApplication) {
            let notificationSettings = UIUserNotificationSettings(
                types: [.badge, .sound, .alert], categories: nil)
            application.registerUserNotificationSettings(notificationSettings)
        }

        func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
            if notificationSettings.types != UIUserNotificationType() {
                application.registerForRemoteNotifications()
            }
        }

        // [START receive_message]
        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                         fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
            // If you are receiving a notification message while your app is in the background,
            // this callback will not be fired till the user taps on the notification launching the application.
            // TODO: Handle data of notification

            // Print message ID. add Toast
            print(userInfo);

            print(application.keyWindow?.visibleViewController() ?? "")

            print("Message ID: \(userInfo["gcm.message_id"]!)")


            // Print full message.
            print("%@", userInfo)
        }
        // [END receive_message]



        func applicationDidBecomeActive(_ application: UIApplication) {
            connectToFcm()
        }

        // [START disconnect_from_fcm]
        func applicationDidEnterBackground(_ application: UIApplication) {
            //        FIRMessaging.messaging().disconnect()
            //        print("Disconnected from FCM.")
        }

        func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

        }

        // [END disconnect_from_fcm]


// [START ios_10_message_handling]
@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
        // Print message ID.
        print("Message ID: \(userInfo["gcm.message_id"]!)")
        // Print message ID. add Toast

        // Print full message.
        print("%@", userInfo)
        // Print full message.
        print("%@", userInfo)
    }
}

extension AppDelegate : FIRMessagingDelegate {
    // Receive data message on iOS 10 devices.
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        print("%@", remoteMessage.appData)
    }
}

// [END ios_10_message_handling]

Référence: https://firebase.google.com/docs/cloud-messaging/ios/device-group

j'Espère que cela va vous aider.

1
répondu Yuyutsu 2017-09-12 05:47:42