【问题标题】:iOS Swift Firebase InstanceID token returns Nil at first timeiOS Swift Firebase InstanceID 令牌首次返回 Nil
【发布时间】:2017-09-17 23:18:06
【问题描述】:

我在我的应用中使用 Firebase 通知。当我第一次安装我的应用程序时,FIRInstanceID.instanceID().token() 返回 nil,但下次它不会返回 nil。除了这个,一切都做得很完美。

代码如下:

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.")
            }
        }
    }
}

在远程页面中我正在调用 Firebase InstanceID 令牌

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

但第一次它返回 nil 值。

【问题讨论】:

  • 你能展示一些你尝试过的代码吗!
  • 在 cmets 中有类似问题的答案:stackoverflow.com/q/40859930/4815718
  • @BobSnyder 如何为密钥 firInstanceIDTokenRefresh 添加观察者以检索最新的令牌
  • 其他人必须回答。我不知道。
  • 你是使用APNS和FCM还是只使用FCM

标签: ios firebase swift3 instanceid


【解决方案1】:

需要在AppDelegate File中添加这行代码 didFinishLaunchingWithOptions function

FirebaseApp.configure() 之前调用 application.registerForRemoteNotifications()

  1. 像这样。 application.registerForRemoteNotifications() FirebaseApp.configure()

【讨论】:

    【解决方案2】:

    最后我得到了一些解决方案。 Firebase 需要一些时间才能连接到 FCM。所以我所做的是,如果FIRInstanceID.instanceID().token() 返回 nil,我会在 5 秒后更新我的代码。 Firebase 将在 5 秒内连接到 FCM。这不是完美的解决方案,但现在这是解决它的唯一方法。

    【讨论】:

    • 你能展示一下这个解决方案的代码吗?我也面临同样的问题。
    【解决方案3】:

    更改FIRApp.configure()的顺序并尝试一次,更多信息您可以获取示例here

    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
    }
    

    在令牌是否到来时对该委托进行检查

    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()
    
        }
    

    最后像这样连接FCM

    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.")
      }
    }
      }
    

    【讨论】:

    • @KavinKumarArumugam - 你修改了哪一行,
    • 很抱歉,我仍然面临这个问题。仍然 FIRInstanceID.instanceID().token() 第一次返回 nil 。我修改了tokenRefreshNotificationconnectToFcm()
    • 如果仍然不能解决您的问题,为什么会被接受?
    猜你喜欢
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多