ios - Swift firebase 推送通知无法以零错误工作?

标签 ios swift firebase firebase-cloud-messaging

我尝试创建推送通知,我成功生成了 APNs 身份验证 key ,并将其上传到 firebase 以及其中的所有内容。我在我的应用程序委托(delegate)中添加了一些函数和委托(delegate),如下所示:

   let notificationCenter = UNUserNotificationCenter.current()//Yeni
    notificationCenter.delegate = self//yeni

    // [START set_messaging_delegate]
    Messaging.messaging().delegate = self as? MessagingDelegate
    // [END set_messaging_delegate]
    // Register for remote notifications. This shows a permission dialog on first run, to
    // show the dialog at a more appropriate time move this registration accordingly.
    // [START register_for_notifications]
    if #available(iOS 10.0, *) {

        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }
    application.registerForRemoteNotifications()



// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    // 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
    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }
    // Print full message.
    print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (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
    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }
    // Print full message.
    print(userInfo)
    completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Unable to register for remote notifications: \(error.localizedDescription)")
}
// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the FCM registration token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("APNs token retrieved: \(deviceToken)")
    // With swizzling disabled you must set the APNs token here.
    // Messaging.messaging().apnsToken = deviceToken
}

以及这些代码扩展:

// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
    // Receive displayed notifications for iOS 10 devices.


   @available(iOS 10.0, *)
   func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        // With swizzling disabled you must let Messaging know about the message, for Analytics
        // Messaging.messaging().appDidReceiveMessage(userInfo)
        // Print message ID.
    completionHandler([.alert, .sound])
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }
        // Print full message.
        print(userInfo)
        // Change this to your preferred presentation option
        completionHandler([])
    }


}


extension AppDelegate : MessagingDelegate {
    // [START refresh_token]
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")
        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
        // TODO: If necessary send token to application server.
        // Note: This callback is fired at each app startup and whenever a new token is generated.
    }
    // [END refresh_token]
    // [START ios_10_data_message]
    // Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
    // To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Received data message: \(remoteMessage.appData)")
    }
    // [END ios_10_data_message]
}

在这一点上我找不到任何问题。我在 firebase 中创建了新的推送通知,但无法从我的设备访问它。我已经一遍又一遍地阅读文档,但我在代码中找不到任何问题。为什么会出现这种情况呢?我的错在哪里?

最佳答案

您的应用程序中添加了 PushNotifications 功能吗?

您的 Firebase Messaging 配置正确吗?

您是否上传了正确的 APNs 证书?

关于ios - Swift firebase 推送通知无法以零错误工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60187605/

相关文章:

swift - 如何在元组上定义后缀运算符?

ios - UITextField 返回键在 ViewController 中进行更改?

android - Firebase ML Kit : "Internal Error" Exception, 但良好的输入和良好的配置

java - Android Studio 无法在没有 Cast 的情况下构建,但应用程序会因 Cast 而崩溃

firebase - 方法 'document' 没有为类型 'CollectionReference' 定义。 flutter/火力基地

objective-c - id 确认了一个协议(protocol),但是在哪里实现呢?

ios - 向 NSMutableArray 添加对象不起作用

arrays - 如何在此 for 循环中将 'Cannot convert value of type ' String' 修复为预期参数类型 'Int'

iphone - 给pdf添加注释

iphone - NSMutableArray大小的监听器和观察器