web-dev-qa-db-ja.com

Firebase(FCM)がAPNSトークンのフェッチに失敗しましたエラードメイン= com.firebase.iidコード= 1001

通知にFCMを使用しようとしています。
しかし、_<FIRInstanceID/WARNING>_ APNSトークンのフェッチに失敗しましたエラーDomain=com.firebase.iid Code=1001 "(null)"が発生したため、通知を受け取ることができません。どうしたの?

コンソールでは、
APNSトークンError Domain=com.firebase.iid Code=1001 "(null)"のフェッチに失敗しました

以下はAppdelegateの私のコードです

_import UIKit
import CoreData
import Alamofire
import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    var badgeCount : Int = 0;

    enum BasicValidity : String {
        case Success = "basicInfo"
        case Fail = "OauthAuthentificationError"
    }

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.


        let uns: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(uns)
        application.registerForRemoteNotifications()

        FIRApp.configure()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), name: kFIRInstanceIDTokenRefreshNotification, object: nil)

        if let token = FIRInstanceID.instanceID().token() {
            sendTokenToServer(token)
            print("token is < \(token) >:")
        }

        return true
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData){


        print("didRegisterForRemoteNotificationsWithDeviceToken()")

        // if FirebaseAppDelegateProxyEnabled === NO:
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .Sandbox)

        print("APNS: <\(deviceToken)>")
    }

    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError){

         print("Registration for remote notification failed with error: \(error.localizedDescription)")
    }

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


        print("didReceiveRemoteNotification()")

        //if FirebaseAppDelegateProxyEnabled === NO:
        FIRMessaging.messaging().appDidReceiveMessage(userInfo)

       // handler(.NoData)

    }

    // [START refresh_token]
    func tokenRefreshNotification(notification: NSNotification) {
        print("tokenRefreshNotification()")
        if let token = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(token)")
            sendTokenToServer(token)
            FIRMessaging.messaging().subscribeToTopic("/topics/global")
            print("Subscribed to: /topics/global")
        }
        connectToFcm()
    }
    // [END refresh_token]

    func sendTokenToServer(currentToken: String) {
        print("sendTokenToServer() Token: \(currentToken)")
        // Send token to server ONLY IF NECESSARY
    }

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

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    // [START disconnect_from_fcm]
    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

        FIRMessaging.messaging().disconnect()
        print("Disconnected from FCM.")
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

       // UIApplication.sharedApplication().applicationIconBadgeNumber = 0
         connectToFcm()

    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }
_
  • バンドルIDを使用して通知を送信すると、Firebaseconsolから通知を受け取ることができます。しかし、サーバーがトークンを使用して特定のデバイスに通知を送信するかどうかを取得できません。
17
kimpro

私にとって、私はそれを機能させるために次の泥棒を試しました:

  • 機能の再有効化->プッシュ通知、キーチェーン共有、バックグラウンドモード->リモート通知
  • アプリを再インストールします(これにより、新しい更新トークンが生成されます。以降の実行でも同じになるため、アプリを実行するたびに印刷されない場合があります)。
  • Firebaseコンソール->プロジェクト設定->クラウドメッセージングに正しい.p12ファイルがアップロードされていることを確認します
  • Appleデベロッパセンターでプロビジョニングプロファイルを再確認します(iOSデベロッパプロビジョニングプロファイルを再度アクティブ化する必要がありました。)

それでも警告が表示される場合がありますが、更新トークンを使用してFirebaseコンソールから通知を送信しようとすると機能します。

5
Rujoota Shah

リモート通知の配信に使用しているサーバーに、FCMトークンの古いレコードがあるようです。 Google FCMのドキュメントには、次の場合にFCMトークンをローテーション(変更)できると記載されています。

  • アプリは新しいデバイスに復元されます
  • ユーザーがアプリをアンインストール/再インストールします
  • ユーザーはアプリデータをクリアします。

彼らは、デリゲートコールバックメソッドを使用してこのトークンのサーバーのレコードを更新することをお勧めします。

func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    // Send the token to your server here
}

その方法は私にはうまくいかなかったので、アプリを起動するたびに手動で更新する必要がありました(ローテーションが常に瞬時に行われるとは限らないため、約20〜25秒の遅延の後)。これは次の方法で実行できます。

let token = Messaging.messaging().fcmToken  // Send this to your server

これらの変更後も警告コンソールのログメッセージが表示されますが、プッシュ通知は毎回完全に機能します。

0
Peza