在iOS 12上收到但在iOS 13上没有收到的Firebase通知 [英] Firebase notifications received on iOS 12 but not received on iOS 13

查看:134
本文介绍了在iOS 12上收到但在iOS 13上没有收到的Firebase通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已发送但未在iOS 13上收到并在iOS 12上收到的Firebase推送通知

Firebase push notifications sent but not received on iOS 13 and received on iOS 12

我的带有Swift 5的xcode版本11.4

My xcode version 11.4 with Swift 5

我在iOS 12.4.2、13.4和13.4.1上进行了测试

I did the test on iOS 12.4.2, 13.4 and 13.4.1

在任何应用程序状态(前台,后台和关闭状态)都未收到通知

The notifications not received in any app state (foreground, background and closed)

我为我的项目添加了一个Firebase项目,并使用APNs身份验证密钥和APNs证书这两种方式与APNS连接

I added a firebase project for my project and connected with APNS using both ways APNs auth key and APNs Certificates

我尝试了Firebase通知编写器,并得到了相同的结果

I tried the firebase notification composer and got the same result

这是我的AppDelegate类代码:

Here is my AppDelegate class code:

import UIKit
import UserNotifications
import Firebase
import NMAKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    let gcmMessageIDKey = "gcm.message_id"

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

        // Override point for customization after application launch.

        //Firebase
        FirebaseApp.configure()

        // [START set_messaging_delegate]
        Messaging.messaging().delegate = self
        // [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

            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()

        // [END register_for_notifications]

        return true
    }

    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 invalidate graphics rendering callbacks. Games should use this method to pause the game.

    }

    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.            
    }

    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.
    }

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


    // MARK: UISceneSession Lifecycle

    @available(iOS 13.0, *)
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    @available(iOS 13.0, *)
    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }

    // [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) {

        var token = ""

        for i in 0..<deviceToken.count {
            token += String(format: "%02.2hhx", arguments: [deviceToken[i]])
        }

        print("Token: ", token)

        print("APNs token retrieved: \(token)")
        //print("content---\(token)");

        //APNS token // not firebase token
        UserDefaults.standard.set(token, forKey: kAPNSToken)
        UserDefaults.standard.synchronize()

        print(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.
    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.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)


        // Change this to your preferred presentation option
        completionHandler([])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {

        let userInfo = response.notification.request.content.userInfo

        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)

        completionHandler()
    }
}
// [END ios_10_message_handling]

extension AppDelegate : MessagingDelegate {

    // [START refresh_token]
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {

        print("Firebase registration token: \(fcmToken)")

        let dataDict:[String: String] = ["token": fcmToken]

        UserDefaults.standard.set(fcmToken, forKey: kFCMToken)
        UserDefaults.standard.synchronize()

        NotificationCenter.default.post(name: CustomNotification.fcmToken, object: nil, userInfo: dataDict)

    }
    // [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]
}

...

以下是我的应用功能:

Here are my app capabilities:

...

我阅读了有关iOS 13推送通知更改的文章:

I read this article about iOS 13 push notifications changes :

影响的OS 13和Xcode 11更改推送通知

(关于优先级和apns-push型)

(regarding priority and apns-push-type)

我没有运气就尝试了以下有效载荷(并尝试了许多不同的有效载荷形式):

I tried the following payload (and tried many different payloads forms) with no luck:

{
    "to": "d2qB-YP_c0B0giLCUFKf1A:APA91bEe....",
    "message": {
        "notification": {
            "title": "Match update",
            "body": "Arsenal goal in added time, score is now 3-0"
        },
        "android": {
            "ttl": "86400s",
            "notification": {
                "click_action": "OPEN_ACTIVITY_1"
            }
        },
        "apns": {
            "headers": {
                "apns-priority": "5",
                "apns-push-type": "background"
            },
            "payload": {
                "aps": {
                    "category": "NEW_MESSAGE_CATEGORY"
                }
            }
        },
        "webpush": {
            "headers": {
                "TTL": "86400"
            }
        }
    }
}

我还使用了以下有效载荷:

I used also the following payloads:

{
    "to": "d2qB-YP_c0B0giLCUFKf1A:APA91bEe....",
    "notification": {
        "title": "Match update",
        "body": "Arsenal goal in added time, score is now 3-0"
    }
}

还有

{
    "to": "eyjFrVn6iEagjBHdxb9sDN.....",
    "notification": {
        "title": "my title here",
        "text": "body here here",
        "sound": "default",
        "badge": 1
    },
    "data": {
        "custom": "my custom message"
    }
}

不幸的是,我得到了相同的结果.

And unfortunately, I got the same result.

推荐答案

Firebase中似乎有一个问题-使用auth key方法(至少在我的情况下具有以下信息)的APNS集成

It looked like there is an issue in Firebase - APNS integration using the auth key method (at least for my case with the bellow information)

在针对iOS 12.4.2、13.4和13.4.1的XCode版本11.4上进行的测试

The test made on XCode version 11.4 for iOS 12.4.2, 13.4 and 13.4.1

使用身份验证密钥时,Firebase推送通知中存在问题,应改为使用p12证书

我检查了直接的APNS推送通知(没有Firebase),效果很好

I checked direct APNS push notifications (without firebase) it's working fine

我还使用2种方法检查了APNS身份验证密钥和p12证书,但它适用于p12证书,但不适用于身份验证密钥

I checked also using 2 methods APNS auth key and p12 certificates, it worked on p12 certificates but not for auth key

这篇关于在iOS 12上收到但在iOS 13上没有收到的Firebase通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆