Подтвердить что ты не робот

Firebase Не удалось получить токен APNS Ошибка домена = com.firebase.iid Код = 1001 "(null)"

2016-08-22 18:34:50.108: <FIRInstanceID/WARNING> FIRInstanceID AppDelegate proxy enabled, will swizzle app delegate remote notification handlers. To disable add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-08-22 18:34:50.106 YAKKO[4269:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see ...)
2016-08-22 18:34:50.114: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
2016-08-22 18:34:50.120: <FIRMessaging/INFO> FIRMessaging library version 1.1.1
2016-08-22 18:34:50.125: <FIRMessaging/WARNING> FIRMessaging AppDelegate proxy enabled, will swizzle app delegate remote notification receiver handlers. Add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-08-22 18:34:50.144 YAKKO[4269:] <FIRAnalytics/INFO> Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
2016-08-22 18:34:50.188 YAKKO[4269:] <FIRAnalytics/INFO> Firebase Analytics enabled

Этот вопрос задавали раньше. Но я все еще не понимаю, как это исправить. Уведомления не работают, и единственное, что у меня есть, это строка: Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"

Я дважды проверил, что я загрузил правильные файлы.p12 в firebase. Я перешел в Target-> → Capabilities-> Фон Modes-> remote-notifications и ON Я дважды проверил, что мой идентификатор пакета соответствует GoogleService-Info.plist

Вот мой AppDelegate.swift

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

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    print("DEVICE TOKEN = \(deviceToken)")
    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                 fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification
    FIRMessaging.messaging().appDidReceiveMessage(userInfo)

    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print("%@", userInfo)
}
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.")
        }
    }
}

Я предполагаю, что он должен работать без этих двух последних методов, но я все равно помещал их туда (согласно утверждениям печати, они не выглядят так, как будто они вызываются).

Я называю registerForRemoteNotifications:

static func registerForNoties(){

    let notificationTypes: UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
    let pushNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(pushNotificationSettings)
    UIApplication.sharedApplication().registerForRemoteNotifications()
}

И я вижу, что устройствоToken напечатано на консоли. Но я все еще получаю эту проблему с FireBase. Любые идеи о других вещах, которые я могу проверить?

4b9b3361

Ответ 1

Я попытался создать простое приложение на основе примера Firebase/Quickstart-iOS для iOS (Swift), и у меня была такая же проблема: Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)".

Я не смог получить уведомление, когда приложение было в фоновом режиме. Итак, я нашел решение, которое работало для меня здесь: https://github.com/firebase/quickstart-ios/issues/103

В основном, я добавил этот метод:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
            print("Handle push from background or closed" );
            print("%@", response.notification.request.content.userInfo);
        }

... и эта строка кода:

application.registerForRemoteNotifications()

По-видимому, пример, написанный в Objective-C, отлично работает, но в примере в Swift отсутствуют некоторые фрагменты кода, и он не работает так, как ожидалось...

Ответ 2

Попробуйте обновить Firebase/Core до v3.4.4, для меня были установлены непредвиденные ошибки. В противном случае попытайтесь избежать вызова unregisterForRemoteNotifications. После этого вызова вы больше не можете регистрировать устройство, чтобы нажимать уведомления. Кроме того, попробуйте установить FirebaseAppDelegateProxyEnabled в NO в файле info.plist. Я думаю, что есть ошибки с их методом swizzling.

Ответ 3

Вызовите этот метод, вы получите токен устройства. И я вижу, что deviceToken напечатано на консоли.

dispatch_async(dispatch_get_main_queue(),
{
     global.appdel.tokenRefreshNotification()
})