web-dev-qa-db-fra.com

le jeton iOS Swift Firebase InstanceID renvoie la valeur Nil pour la première fois.

J'utilise la notification Firebase dans mon application. Lorsque j’installe mon application pour la première fois, FIRInstanceID.instanceID().token() renvoie nil, mais ne le sera pas à la prochaine fois. Tout est parfait sauf ça.

Voici le code:

import UIKit
import Firebase
import FirebaseMessaging
import FirebaseInstanceID
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate
{

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
        //Configuring Firebase
        FIRApp.configure()
if #available(iOS 10.0, *)
        {
            print("Test")
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self
            UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { (granted, error) in
                if granted
                {
                    //self.registerCategory()
                }
            }
            // For iOS 10 data message (sent via FCM)
            FIRMessaging.messaging().remoteMessageDelegate = self
        }
        else
        {
            let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
        return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
    {
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.prod)
    }
func tokenRefreshNotification(notification: NSNotification)
    {
        if let refreshedToken = FIRInstanceID.instanceID().token()
        {
            print("InstanceID token: \(refreshedToken)")
        }
        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }

    func connectToFcm()
    {
        FIRMessaging.messaging().connect { (error) in
            if (error != nil)
            {
                print("Unable to connect with FCM. \(error)")
            }
            else
            {
                print("Connected to FCM.")
            }
        }
    }
}

Dans la page distante, j'appelle le jeton d'instance ID de Firebase.

let token = FIRInstanceID.instanceID().token()

Mais à la première fois, il ne retourne aucune valeur.

5

changer l'ordre de FIRApp.configure() et essayer une fois, pour plus d'informations, vous pouvez obtenir l'échantillon ici

func application(_ application: UIApplication,
               didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
// [START register_for_notifications]
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 })

  // For iOS 10 data message (sent via FCM)
  FIRMessaging.messaging().remoteMessageDelegate = self

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

application.registerForRemoteNotifications()

// [END register_for_notifications]
FIRApp.configure()

// [START add_token_refresh_observer]
// Add observer for InstanceID token refresh callback.
NotificationCenter.default.addObserver(self,
    selector: #selector(self.tokenRefreshNotification),
    name: .firInstanceIDTokenRefresh,
    object: nil)
// [END add_token_refresh_observer]
return true
}

sur ce chèque de délégué une fois que le jeton est venu ou non

func tokenRefreshNotification(notification: NSNotification) {
      //  print("refresh token call")
        guard let contents = FIRInstanceID.instanceID().token()
        else {
            return
        }
           // let refreshedToken = FIRInstanceID.instanceID().token()!
            print("InstanceID token: \(contents)")

           // UserDefaults.standardUserDefaults().set(contents, forKey: "deviceToken");
            // Connect to FCM since connection may have failed when attempted before having a token.

            connectToFcm()

    }

enfin connectez le FCM comme

func connectToFcm() {
// Won't connect since there is no token
guard FIRInstanceID.instanceID().token() != nil else {
  return
}

// Disconnect previous FCM connection if it exists.
FIRMessaging.messaging().disconnect()

FIRMessaging.messaging().connect { (error) in
  if error != nil {
    print("Unable to connect with FCM. \(error?.localizedDescription ?? "")")
  } else {
    print("Connected to FCM.")
  }
}
  }
4
Anbu.Karthik

Enfin, j'ai une solution pour cela. Firebase mettra un certain temps à se connecter à FCM. Donc, ce que j’ai fait, c’est que mon code est mis à jour au bout de 5 secondes si FIRInstanceID.instanceID().token() renvoie zéro. Dans les 5 secondes qui suivent, Firebase sera connecté au FCM. Ce n'est pas la solution parfaite, mais c'est maintenant le seul moyen de la résoudre.

1