【问题标题】:Firebase notifications received on iOS 12 but not received on iOS 13在 iOS 12 上收到 Firebase 通知,但在 iOS 13 上未收到
【发布时间】:2020-08-17 13:01:21
【问题描述】:

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

我的 xcode 版本 11.4 与 Swift 5

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

在任何应用状态(前台、后台和关闭)下都没有收到通知

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

我尝试了 firebase 通知作曲家并得到了相同的结果

这是我的 AppDelegate 类代码:

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

...

以下是我的应用功能:

...

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

OS 13 and Xcode 11 Changes That Affect Push Notifications

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

我尝试了以下有效载荷(并尝试了许多不同的有效载荷形式),但没有成功:

{
    "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"
            }
        }
    }
}

我还使用了以下负载:

{
    "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"
    }
}

不幸的是,我得到了同样的结果。

【问题讨论】:

  • 嗨艾哈迈德。您使用的有效负载结构适用于 FCM v1。您可以尝试使用 legacy 看看您是否仍然无法发送到这两个版本? Here's a sample to send a push using Postmanto 不再是 v1 有效负载中的保留键。奇怪的是它在 iOS13 上不起作用,也可能是操作系统级别的限制,但请告诉我它是怎么回事。
  • 谢谢你。为了您的澄清,我使用了 Firebase 作曲家,并且收到了 iOS 12 的消息,但不幸的是,iOS 13 没有收到消息
  • 另外,我尝试使用 legacy 并得到相同的结果 {"to":"eyjFrVn6iEagjBHdxb9sDN.....","notification":{"title":"my title here","text ":"这里是正文"}} jsoneditoronline.org/…
  • 我还使用了不同的样式,例如:jsoneditoronline.org/…jsoneditoronline.org/…
  • 可能是 iOS 13 本身的问题:github.com/FirebaseExtended/flutterfire/issues/1041 另外,您看到解决方案了吗here?也许在有效负载中添加选项可能会有所作为。

标签: ios firebase push-notification ios13 ios12


【解决方案1】:

Firebase 中似乎存在问题 - 使用 auth 密钥方法进行 APNS 集成(至少对于我的情况,有以下信息)

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

使用身份验证密钥时 Firebase 推送通知出现问题,应改用 p12 证书

我检查了直接 APNS 推送通知(没有 firebase),它工作正常

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

【讨论】:

  • 经过仔细检查和验证的答案,我可以确认Firebase - iOS 13的Auth Key方法存在问题
  • 你为什么要删除你的其他答案?
  • 我以更专业的方式更新了书面答案,虽然它是正确的,但我对之前的答案投了反对票,我尝试编辑答案,但不幸的是,尽管答案经过测试,但投反对票并未被删除并仔细验证
  • 是的,很公平 - 否决票是问题所在!我认为您在这里的方法是正确的,对于噪音感到抱歉。
  • 天哪,这是 Firebase 文档中的一个大缺陷。你不知道我用了多少小时来调试这个问题。非常感谢,没想到使用 SSL 证书可以解决这个问题,但它做到了!
猜你喜欢
  • 1970-01-01
  • 2022-07-27
  • 2021-09-16
  • 2017-12-24
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 2016-03-08
  • 2019-04-12
相关资源
最近更新 更多