Firebase Неверный регистрационный токен.Проверьте формат токена - PullRequest
0 голосов
/ 15 мая 2018

Этот вопрос задавали и отвечали много раз прежде, но я не могу понять, что я делаю неправильно.Отправка уведомлений всему приложению из консоли Firebase работает, но если я отправляю на один токен, я получаю сообщение об ошибке в консоли Firebase: «Неверный регистрационный токен Firebase. Проверьте формат токена»

Я тестирую приложение вустройство Iphone.

  • создал новый ключ в https://developer.apple.com/account/ios/authkey/ скачал файл p8
  • получил идентификатор команды из https://developer.apple.com/account/#/membership/
  • загрузил файл .p8 в firebaseконсоль в разделе Настройки / облачные сообщения
  • в .xcworspace в разделе Цели / Возможности / Push-уведомления: ON
  • В файле myproject.entitlements содержится разработка строки среды APS.

ПРИМЕЧАНИЕ. На developer.apple.com в разделе «Идентификаторы приложения», если я нажимаю на идентификатор myApp и прокручиваю вниз, «Настраиваемые уведомления о разработке и разработка» отображаются желтым, а не зеленым цветом.

Xcode version Version 8.3.3 (8E3004b), Swift 3.0
pod file    
pod 'Firebase', '~> 3.9.0'
pod 'Firebase/Auth', '~> 3.9.0'
pod 'Firebase/Database', '~> 3.9.0'
pod 'Firebase/Storage'
pod 'Firebase/Messaging'

Using Firebase (3.9.0)
Using FirebaseAnalytics (3.5.1)
Using FirebaseAuth (3.0.6)
Using FirebaseCore (3.4.4)
Using FirebaseDatabase (3.1.0)
Using FirebaseInstanceID (1.0.9)
Using FirebaseMessaging (1.2.1)
Using FirebaseStorage (1.0.4)
Using GTMSessionFetcher (1.1.12)
Using GoogleInterchangeUtilities (1.2.2)
Using GoogleSymbolUtilities (1.1.2)
Using GoogleToolboxForMac (2.1.3)



import UIKit
import Firebase
import FirebaseCore
import FirebaseMessaging
import FirebaseInstanceID
import UserNotifications

 @UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

 var window: UIWindow?


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

  FIRApp.configure()

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

  //obtain the user’s permission to show any kind of notification
  registerForPushNotifications()
  return true
}//end of didFinishLaunchingWithOptions


 //obtain the user’s permission to show any kind of notification
 func registerForPushNotifications() {

  // iOS 10 support
  if #available(iOS 10, *) {
    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in
        print("Permission granted: \(granted)")

        guard granted else {return}
        self.getNotificationSettings()
    }
}
    // iOS 9 support
 else if #available(iOS 9, *){UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
    self.getNotificationSettings()
}
    // iOS 8 support
  else if #available(iOS 8, *) {UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
    self.getNotificationSettings()
 }
    // iOS 7 support
else {
    UIApplication.shared.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
 }
}//end of registerForPushNotifications()



  //if user decliens permission when we request authorization to show notification
  func getNotificationSettings() {
 UNUserNotificationCenter.current().getNotificationSettings { (settings) in

     print("settings.authorizationStatus is \(settings.authorizationStatus)")
    guard settings.authorizationStatus == .authorized else {return}
    UIApplication.shared.registerForRemoteNotifications()
   }
 }


func tokenRefreshNotification(notification: NSNotification) {
 let refereshToken = FIRInstanceID.instanceID().token()
 print("instance ID token is \(refereshToken)")
 prints: c-_B0W1AKX0:APA91bHBCtFhGtteH1r2y7c8gpUJpfrgDZYtncFmxZQht_wBDWk9Stdf78aMqUctKYU_OlIkmMNW-KLP68_IhdZCM2WxcN4fU1XkoIVNCGTvBogzSpgt4IkveLbK7rNX7pQTfmP72MfV

 connectToFcm()
}


 func connectToFcm() {
   FIRMessaging.messaging().connect { (error) in
      if error != nil  {
         print("unable to connect to FCM")
     }else {
         print("connected to FCM")
     }
   }
 }

}//end of AppDelegate    

enter image description here enter image description here enter image description here enter image description here enter image description here

1 Ответ

0 голосов
/ 22 мая 2018

Когда я создавал приложение в консоли Firebase, при вводе идентификатора пакета я набрал опечатку.
Я никогда не задумывался о его проверке, поскольку использовал службы базы данных Firebase и все операции CRUD работали, как и ожидалось, ноидентификатор Bundle в Xcworkspace и BundleID приложения firebase были не совсем одинаковыми.
Было бы здорово, если бы кто-нибудь из Google мог сказать причину, по которой чтение / запись из клиентского приложения работала, как ожидалось, дажехотя идентификатор пакета был неверен в консоли Firebase.

Как я обнаружил опечатку?
Сначала я загрузил в консоль Firebase файл p8, который был загружен с developer.apple.com, и ошибки не было.
Позже я решил использовать сертификаты (по-старому), и когда я попытался загрузить Apple Push Notification service SSL (Sandbox) - Development, я получил ошибку Идентификатор комплекта сертификатов не совпадает с идентификатором вашего приложения

...