ios APNS Firebase 通知无法获取令牌

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37438369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:09:44  来源:igfitidea点击:

APNS Firebase Notification failed to fetch token

iosswiftpush-notificationfirebasefirebase-notifications

提问by Dmitry Kuzin

For Swift3 / iOS10 see this link:

对于 Swift3 / iOS10,请参阅此链接:

ios10, Swift 3 and Firebase Push Notifications (FCM)

ios10、Swift 3 和 Firebase 推送通知 (FCM)

I'm trying to use the Firebase for Notifications and I integrated it exactly as described in the docs. But I don't understand why is doesn't work. When I build my project I see this line:

我正在尝试使用 Firebase 进行通知,我完全按照文档中的描述集成了它。但我不明白为什么不起作用。当我构建我的项目时,我看到这一行:

2016-05-25 16:09:34.987: <FIRInstanceID/WARNING> Failed to fetch default token Error Domain=com.firebase.iid Code=0 "(null)"

This my AppDelegate:

这是我的 AppDelegate:

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    FIRApp.configure()
    FIRDatabase.database().persistenceEnabled = true
     var service: DataService = DataService()
    service.start()
    registerForPushNotifications(application)
    application.registerForRemoteNotifications()
    return true
}

func registerForPushNotifications(application: UIApplication) {
    let notificationSettings = UIUserNotificationSettings(
        forTypes: [.Badge, .Sound, .Alert], categories: nil)
    application.registerUserNotificationSettings(notificationSettings)
}

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    if notificationSettings.types != .None {
        application.registerForRemoteNotifications()
    }
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

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

    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)
    print("Device Token:", tokenString)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)  {
    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

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

采纳答案by Sanandiya Vipul

1.Set Notification Observer in didFinishLaunchingWithOptionsMethod

1.在didFinishLaunchingWithOptions方法中设置通知观察者

2.And Set tokenRefreshNotificationmethod then u get Token in this method.

2.并设置tokenRefreshNotification方法,然后在此方法中获取 Token。

See below Code

见下面的代码

import Firebase
import FirebaseMessaging

override func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
  FIRApp.configure()

      NotificationCenter.default.addObserver(self,
                                                     selector: #selector(self.tokenRefreshNotification(notification:)),
                                                     name: NSNotification.Name.firInstanceIDTokenRefresh,
                                                     object: nil)
}

// NOTE: Need to use this when swizzling is disabled
public func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

  FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
}

func tokenRefreshNotification(notification: NSNotification) {
  // NOTE: It can be nil here
  let refreshedToken = FIRInstanceID.instanceID().token()
  print("InstanceID token: \(refreshedToken)")

  connectToFcm()
}

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

public func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
  print(userInfo)
}

回答by starlord_amj

I too had the same issue and nothing worked for me. But all you have to do is go to your firebase console and then find your project and goto its settings, there check in its cloud messaging tab and upload your .p12 certificate into that.

我也有同样的问题,但对我没有任何作用。但是您所要做的就是转到您的 firebase 控制台,然后找到您的项目并转到其设置,然后检查其云消息选项卡并将您的 .p12 证书上传到其中。

thats it! happy coding :)

就是这样!快乐编码:)

回答by Moose

1 - Have you correctly configured your certificates as specified in the google documentation ( I won't recall the process here, it is quite long... )? ( https://firebase.google.com/docs/cloud-messaging/ios/certs#configure_an_app_id_for_push_notifications)

1 - 您是否按照 google 文档中的说明正确配置了您的证书(我不记得这里的过程,它很长......)?(https://firebase.google.com/docs/cloud-messaging/ios/certs#configure_an_app_id_for_push_notifications

2 - I've been through some difficulties when setting up FCM. Once I thought everything was ok but notifications were still not working, I've decided to completely remove the app from the phone, clean my build folder and reinstall the whole thing. After that, it was working.

2 - 我在设置 FCM 时遇到了一些困难。一旦我认为一切正常但通知仍然不起作用,我决定从手机中完全删除该应用程序,清理我的构建文件夹并重新安装整个程序。在那之后,它开始工作了。

3 - The app was receiving notifications, but I was still getting the "Failed to fetch default token..." message. It disappeared after a while. Don't ask me why!

3 - 应用程序正在接收通知,但我仍然收到“无法获取默认令牌...”消息。过了一会儿就消失了。不要问我为什么!

This is not really a proper answer, I just share my experience because I know configuring notification is not easy and every clue is welcome. So maybe this one can help. Cheers :)

这不是一个真正的正确答案,我只是分享我的经验,因为我知道配置通知并不容易,欢迎提供每一条线索。所以也许这个可以帮助。干杯:)

回答by michael chein

After trying all of the above (and anything I could find elsewhere), what resolves the problem for me is to move

在尝试了上述所有方法(以及我在其他地方可以找到的任何内容)之后,对我来说解决问题的方法是移动

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

to be called when pressing a button, and not on app loading.

在按下按钮时调用,而不是在应用加载时调用。

I know it's probably not the most elegant solution, but it's good enough for debugging purposes. Im guessing the token is not available immediately by the server, and takes some time to be generated.

我知道这可能不是最优雅的解决方案,但对于调试目的来说已经足够了。我猜测令牌不能立即被服务器使用,并且需要一些时间来生成。

回答by Peza

The answers above cover most of the issue, but I had the same issue and I found the following info useful:

上面的答案涵盖了大部分问题,但我遇到了同样的问题,我发现以下信息很有用:

  1. Firebase can 'rotate'(change) a user's FCM token at any time. This is the 128 character ID that your server will use to send the push notification to the device.

  2. Firebase docs say best practice is to use a delegate to monitor for changes with the delegate callback method:

    - (void)messaging:(nonnull FIRMessaging *)messaging didRefreshRegistrationToken:(nonnull NSString *)fcmToken
    
  1. Firebase 可以随时“轮换”(更改)用户的 FCM 令牌。这是您的服务器将用于向设备发送推送通知的 128 个字符的 ID。

  2. Firebase 文档说最佳实践是使用委托来监视委托回调方法的更改:

    - (void)messaging:(nonnull FIRMessaging *)messaging didRefreshRegistrationToken:(nonnull NSString *)fcmToken
    

[Obj - C]

[对象-C]

func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String)

[Swift]

[迅速]

The delegate method should be called on every change, at which point you can update the record in your server.

应在每次更改时调用委托方法,此时您可以更新服务器中的记录。

  1. Unfortunately that wasn't working for me, I had a delegate but the callback wasn't being invoked. So I had to resort to manually updating the token on each app launch (as suggested by @micheal chein above) as follows:

    NSString *deviceToken = [FIRInstanceID instanceID].token; // Send this to your server
    

    [Obj-C]

    let token = FIRInstanceID.instanceID().token() // Send this to your server
    

    [Swift]

  1. 不幸的是,这对我不起作用,我有一个委托,但没有调用回调。所以我不得不在每次应用程序启动时手动更新令牌(如上面@micheal chein 所建议的),如下所示:

    NSString *deviceToken = [FIRInstanceID instanceID].token; // Send this to your server
    

    [对象-C]

    let token = FIRInstanceID.instanceID().token() // Send this to your server
    

    [迅速]

** Important: update the token after a delay (20-25s), as the rotation can sometimes only reflect after some time. You can use a timer for this.

** 重要提示:延迟(20-25 秒)后更新令牌,因为轮换有时只能在一段时间后反映出来。您可以为此使用计时器。

  1. After this I still get the APNS warning/error message:

    2017-06-06 09:21:49.520: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
    
  1. 在此之后,我仍然收到 APNS 警告/错误消息:

    2017-06-06 09:21:49.520: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
    

BUT, push notifications work every time without fail. So I think that log message is a bit off (possibly mistimed). If you can get option 2 to work for you, definitely do that!

但是,推送通知每次都可以正常工作。所以我认为日志消息有点不对(可能是不合时宜)。如果您可以让选项 2 为您工作,那么一定要这样做!

回答by Ro4ch

FCM was working for me then just stopped. I did what Rabs G. suggested and removed the app and installed again and the notifications started working again.

FCM 正在为我工​​作,然后就停止了。我做了 Rabs G. 的建议并删除了该应用程序并再次安装,通知再次开始工作。