0 Replies
      Latest reply on Jul 12, 2019 10:18 AM by InvaDerZim
      InvaDerZim Level 1 Level 1 (0 points)

        i had this issue when trying to get the FCMtoken for the second time, when the user accepts the permissions to push notifications he can log into the app properly, but if decide to unregister from the app, he cannot complete the path again, because he cannot get another FCMtoken

        i already tryed deleting the firebaseApp and get another FirebaseToken

         

        //
                        if let token = InstanceID.instanceID().token() {
                            print("Token : \(token)");
                            UserSingleton.getInstance().pushToken = token
                        } else {
                            print("Error: unable to fetch token");
                        }
        
                        Messaging.messaging().shouldEstablishDirectChannel = true
        
                        print("new token: \(UserSingleton.getInstance().pushToken)")
                        self.dismiss(animated: true, completion: nil)
                        //
                    }
        
                }
        
                func registerFirebaseToken() {
                    if let token = InstanceID.instanceID().token() {
                        print("FIREBASE: Token \(token) fetched")
                    } else {
                        print("FIREBASE: Unable to fetch token");
                    }
        
                    Messaging.messaging().shouldEstablishDirectChannel = true
                }
        
                func unregisterFirebaseToken(completion: @escaping (Bool)->()) {
                    // Delete the Firebase instance ID
                    InstanceID.instanceID().deleteID { (error) in
                        if error != nil{
                            print("FIREBASE: ", error.debugDescription);
                            completion(false)
                        } else {
                            print("FIREBASE: Token Deleted");
                            completion(true)
                        }
                    }
        

         

         

        when the user unregister from the app this code runs and gives this :

         

        5.17.0 - [Firebase/InstanceID][I-IID003009] Failed to fetch default token Error Domain=com.firebase.iid Code=2006 "(null)"
        

        this is my FirebaseToken Class:

        import Foundation
        import Firebase
        import UserNotifications
        import FirebaseInstanceID
        import FirebaseMessaging
        
        @objc protocol CallbackToken {
            func onGetToken(token: String)
        }
        
        class FirebaseToken: UIResponder {
        
            let gcmMessageIDKey = "gcm.message_id"
            let preferences = UserDefaults.standard
            var appName = ""
            var isFistFireConfigured = false
        
            var delegate: CallbackToken?
        
            func getIdN(_ application: UIApplication, callbackToken:CallbackToken, cGoogleID: String) {
                delegate = callbackToken
        
                if #available(iOS 10.0, *) {
                    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()
        
                self.configureApp(googleID: cGoogleID, iOSID: Constants.iOSID, app: Constants.appName)
        
                Messaging.messaging().delegate = self
            }
        
            func configureApp(googleID: String, iOSID: String, app: String) {
                appName = app
                let fireOptions = FirebaseOptions(googleAppID: String(format: "1:%@:ios:%@", googleID, iOSID), gcmSenderID: googleID)
                NSLog("FIREBASE APP ID -> %@", fireOptions)
        
                NSLog("CONFIGURED APP %@ -> %@", appName, fireOptions)
        
                let app = FirebaseApp.app()
                app?.delete({ (true) in
                    NSLog("Firebase app deleted")
                })
                FirebaseApp.configure(options: fireOptions)
            }
        
        
        }
        
        extension FirebaseToken: UNUserNotificationCenterDelegate {
        
            func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
                let userInfo = notification.request.content.userInfo
                if userInfo[gcmMessageIDKey] != nil {
                    NSLog("MESSAGE ID -> %@", self)
                }
        
                NSLog("USER INFO -> %@", userInfo)
                completionHandler([.alert, .badge, .sound])
            }
        
            func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        
                let userInfo = response.notification.request.content.userInfo
        
                if let messageID = userInfo[gcmMessageIDKey] {
                    print("\n4. Message ID: \(messageID)")
                }
        
        
        
                if UIApplication.shared.applicationState == .active {
                    print("Usuario apretó la push cuando la app está activa AppDelegate")
                    print("esto es el mensaje: \(response)")
                    if UserSingleton.getInstance().pushNoti != [:] {
                        if UserDefaults.standard.bool(forKey: "isLogged") == true {
                            UserDefaults.standard.set(true, forKey: "noPresencialForeground")
                            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "noPresencial"), object: nil)
        
        
                        } else {
                            UserDefaults.standard.set(true, forKey: "noPresencialForeground")
                        }
                    }
        
                    else {
                        print("Solo abre la app")
                    }
                } else if UIApplication.shared.applicationState == .inactive {
                    print("Usuario apretó la push cuando la app está INACTIVA AppDelegate")
                    if UserSingleton.getInstance().pushNoti != [:] {
                        if UserDefaults.standard.bool(forKey: "isLogged") == true {
                            UserDefaults.standard.set(true, forKey: "noPresencialForeground")
                            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "noPresencial"), object: nil)
        
                        }
        
                        else {
                            UserDefaults.standard.set(true, forKey: "noPresencialForeground")
                        }
                    } else {
                        print("Solo abre la app")
                    }
                }
                completionHandler()
            }
        
        }
        
        extension FirebaseToken: MessagingDelegate {
        
        
            func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        
                print("Firebase registration token: \(fcmToken)")
        
        
        
                UserSingleton.getInstance().pushToken = fcmToken
        
                isFistFireConfigured = true
        
                preferences.set(fcmToken, forKey: appName)
        
                delegate?.onGetToken(token: fcmToken)
        
                let didSave = preferences.synchronize()
                if !didSave {
                    print("Error al sincronizar las preferencias")
                }
        
                if isFistFireConfigured {
                    configureApp(googleID: Constants.googleIDCobroSPEI, iOSID: Constants.iOSID, app: Constants.appNameCobroSPEI)
                    isFistFireConfigured = false
                }
            }
        
            func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
                print("\nMensaje de datos recibido en primer plano: \(remoteMessage.appData)")
            }
        }