iOS Swift Firebase InstanceID令牌第一次返回零 [英] iOS Swift Firebase InstanceID Token Returns Nil at First Time

查看:343
本文介绍了iOS Swift Firebase InstanceID令牌第一次返回零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用了Firebase通知。当我第一次安装我的应用程序 FIRInstanceID.instanceID()。token()返回nil,但是它不会在下一次返回nil。帮我解决这个问题。

 导入UIKit 
导入Firebase
导入FirebaseMessaging
import FirebaseInstanceID $ b $ class AppDelegate:UIResponder,UIApplicationDelegate,UNUserNotificationCenterDelegate,FIRMessagingDelegate
{

func application(_ application:UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplicationLaunchOptionsKey:Any]? ) - > Bool
{
//配置Firebase
FIRApp.configure()
if #available(iOS 10.0,*)
{
print(Test )
//对于iOS 10显示通知(通过APNS发送)
UNUserNotificationCenter.current()。delegate = self
UNUserNotificationCenter.current()。requestAuthorization(options:[.badge,.sound ,.alert]){(授予,错误)在
如果授予
{
//self.registerCategory()
}
}
//对于iOS 10数据消息(通过FCM发送)
FIRMessaging.messaging()。remoteMessageDelegate = self
}
else
{
let settings:UIUserNotificationSettings = UIUserNotificationSettings(types :[.alert,.badge,.sound],类别:无)
application.registerUserNotificationSettings(settings)
}

applica tion.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(通知:NSNotification)
{
如果让refreshedToken = FIRInstanceID.instanceID()
{
print(InstanceID token:\(refreshedToken))
}
//连接到FCM,因为在有令牌之前尝试连接可能失败。
connectToFcm()
}

func connectToFcm()
{
FIRMessaging.messaging()。connect {(error)in
if (error!= nil)
{
print(无法连接FCM。\(错误))
}
else
{
print(Connected to FCM。)
}
}
}
}

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

  let token = FIRInstanceID.instanceID()。令牌()

但是第一次返回nil值。
<解决方案改变 FIRApp.configure()的顺序并尝试一次,获取更多信息可以得到示例此处

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

//注册远程通知。这显示第一次运行的权限对话框,
//在更合适的时间显示对话框,相应地移动这个注册。
// [START register_for_notifications]
if #available(iOS 10.0,*){
//对于iOS 10显示通知(通过APNS发送)
UNUserNotificationCenter.current()。 delegate = self

let authOptions:UNAuthorizationOptions = [.alert,.badge,.sound]
UNUserNotificationCenter.current()。requestAuthorization(
options:authOptions,
completionHandler:{_,_in})

//对于iOS 10数据消息(通过FCM发送)
FIRMessaging.messaging()。remoteMessageDelegate = self

UIUserNotificationSettings = $ b $ UIUserNotificationSettings(类型:[.alert,.badge,.sound],类别:nil)
application.registerUserNotificationSettings(设置)
}

application.registerForRemoteNotifications()

// [END register_for_notifications]
FIRApp.configure()

// [START add_token_refresh_observer]
//为InstanceID令牌刷新回调添加观察者。
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))
$ b $ // UserDefaults.standardUserDefaults().set(contents,forKey:deviceToken);
//连接到FCM,因为在有令牌之前尝试连接可能失败。
$ b connectToFcm()

}

连接FCM就像

  func connectToFcm(){
//不会连接,因为没有令牌
guard FIRInstanceID.instanceID()。token()!= nil else {
return
}

//断开以前的FCM连接(如果存在)。
FIRMessaging.messaging()。disconnect()

FIRMessaging.messaging()。connect {(error)in
if error!= nil {
print(无法与FCM连接\(error?.localizedDescription ??))
} else {
print(Connected to FCM。)
}
}
}


I am using firebase notification in my app. When I install my app for first time FIRInstanceID.instanceID().token() returns nil, but it won't return nil at next time. Help me to solve this problem. Everything is done perfect except this.Here is the 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.")
            }
        }
    }
}

In Remote Page I am Calling Firebase InstanceID Token

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

But at first time it return nil value.

解决方案

change the order of FIRApp.configure() and try once, for more information you can get the sample 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
}

on that delegate check once the token is comes or not

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

    }

finally connect the FCM like

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

这篇关于iOS Swift Firebase InstanceID令牌第一次返回零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆