ios - Firebase 推送通知 iOS 问题,无法获取 APNS token 错误域=com.firebase.iid 代码=1001 "(null)"

标签 ios swift firebase push-notification firebase-cloud-messaging

我正在尝试为 iOS 实现 Firebase 推送通知,收到此消息:无法获取 APNS token 错误 Domain=com.firebase.iid Code=1001“(null)”

我正在使用Swift 2.3 , Xcode 8 .

我已经在 Firebase 控制台中设置了 APNs SSL 证书,还在 Xcode 应用 > 功能中启用了推送通知,并在后台模式中选中了远程通知选项。 还添加了FirebaseAppDelegateProxyEnabled = NoInfo.plist和正确的Bundle IDGoogleService-Info.plist

发生了一件奇怪的事情,如果我没有在 Xcode App > 功能中启用推送通知,我不会收到错误,它会打印用户信息和 token :( 请帮忙。

下面是我的AppDelegate代码和输出

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

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

    //for Firebase
       // [START register_for_notifications]
    if #available(iOS 10.0, *) {
        let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound]
        UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
            authOptions,
            completionHandler: {_,_ in })
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.currentNotificationCenter().delegate = self
        // For iOS 10 data message (sent via FCM)
        FIRMessaging.messaging().remoteMessageDelegate = self

    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    // [END register_for_notifications]

    FIRApp.configure()

    // Add observer for InstanceID token refresh callback.
    NSNotificationCenter.defaultCenter().addObserver(self,
                                                     selector: #selector(self.tokenRefreshNotification),
                                                     name: kFIRInstanceIDTokenRefreshNotification,
                                                     object: nil)

    return true
}


// [START receive_message]
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

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

    // Print full message.
    print("%@", userInfo)
    print("message comes here end")

}
// [END receive_message]

// [START refresh_token]
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()
}
// [END refresh_token]

// [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 applicationDidBecomeActive(application: UIApplication) {
    connectToFcm()
}

// [START disconnect_from_fcm]
func applicationDidEnterBackground(application: UIApplication) {
    FIRMessaging.messaging().disconnect()
    print("Disconnected from FCM.")
}
// [END disconnect_from_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.
}


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

func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

}

// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

   // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(center: UNUserNotificationCenter,
                                willPresentNotification notification: UNNotification,
                                                       withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
       // Print message ID.
     //   print("Message ID: \(userInfo["gcm.message_id"]!)")

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

extension AppDelegate : FIRMessagingDelegate {
   // Receive data message on iOS 10 devices.
   func applicationReceivedRemoteMessage(remoteMessage: FIRMessagingRemoteMessage) {
        print("%@", remoteMessage.appData)
    }
}

// [END ios_10_message_handling]


--------OUTPUT
2016-10-20 15:50:03.051 ProgrammingHub[2747:916824] WARNING: Firebase Analytics App Delegate Proxy is disabled. To log deep link campaigns manually, call the methods in FIRAnalytics+AppDelegate.h.

2016-10-20 15:50:04.073 ProgrammingHub[2747:916824] [Crashlytics] Version 3.7.2 (112)

2016-10-20 15:50:04.287 ProgrammingHub[2747] <Debug> [Firebase/Core][I-COR000001] Configuring the default app.

2016-10-20 15:50:04.314: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"

2016-10-20 15:50:04.326: <FIRMessaging/INFO> FIRMessaging library version 1.2.0

2016-10-20 15:50:04.380 ProgrammingHub[2747:] <FIRAnalytics/INFO> Firebase Analytics v.3404000 started

2016-10-20 15:50:04.382 ProgrammingHub[2747:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see http:/goo.gl/Y0Yjwu)

2016-10-20 15:50:04.692 ProgrammingHub[2747:916824] INFO: GoogleAnalytics 3.11 -[GAIReachabilityChecker reachabilityFlagsChanged:] (GAIReachabilityChecker.m:159): Reachability flags update: 0X000002

2016-10-20 15:50:04.988 ProgrammingHub[2747:916824] INFO: GoogleAnalytics 3.11 -[GAIReachabilityChecker reachabilityFlagsChanged:] (GAIReachabilityChecker.m:159): Reachability flags update: 0X000002

2016-10-20 15:50:05.208 ProgrammingHub[2747:] <FIRAnalytics/INFO> Firebase Analytics enabled

2016-10-20 15:50:05.391 ProgrammingHub[2747:916926] INFO: GoogleAnalytics 3.11 -[GAIBatchingDispatcher hitsForDispatch] (GAIBatchingDispatcher.m:368): No pending hits.
2016-10-20 15:50:06.166 ProgrammingHub[2747] <Debug> [Firebase/Core][I-COR000019] Clearcut post completed.

最佳答案

尝试将 Firebase/Core 更新到 v3.4.4,它修复了我意外的错误。另外,请避免调用 unregisterForRemoteNotifications。此调用后,您将无法再注册设备来推送通知。

关于ios - Firebase 推送通知 iOS 问题,无法获取 APNS token 错误域=com.firebase.iid 代码=1001 "(null)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40151854/

相关文章:

objective-c - iOS 文本环绕

ios - 从另一个委托(delegate)类中检索 UIColor

ios - Rx swift : Is it bad practice to subscribe to a presented view controllers view model?

ios - 为 ActivityViewController 提供的未知事件项

swift - 重复 iCarousel 的滚动

node.js - 在云函数中处理 HTTP 请求时读取 ECONNRESET 错误

ios - 多个 iOS GET 请求(动态请求数)

ios - UITableView - 背景图像大小和位置问题

javascript - 如何在 firebase 中链接电话号码后重定向?

ios - 适用于 iOS 的多个构建环境的 Firebase crashlytics