Уведомления Firebase, полученные iOS 12, но не полученные iOS 13 - PullRequest
1 голос
/ 03 мая 2020

Firebase pu sh уведомления, отправленные, но не полученные на iOS 13 и полученные на iOS 12

Мой xcode version 11.4 с Swift 5

Я прошел тест на iOS 12.4.2, 13.4 и 13.4.1

Уведомления, не полученные ни в каком состоянии приложения (передний план, фон и закрыто)

Я добавил проект firebase для своего проекта и подключился к APNS используя оба способа ключ аутентификации APN и сертификаты APN

Я попробовал уведомление firebase composer и получил тот же результат

Вот мой код класса 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]
}

...

Вот возможности моего приложения: App Capabilities

...

Я читал эту статью о iOS 13 pu sh изменения уведомлений:

Изменения OS 13 и Xcode 11, которые влияют на Pu sh Уведомления

(относительно приоритета и типа apns-pu sh)

Я попробовал следующую полезную нагрузку (и пробовал много разных форм полезных нагрузок) безуспешно:

{
    "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"
            }
        }
    }
}
* 103 5 * Я также использовал следующие полезные данные:
{
    "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"
    }
}

И, к сожалению, я получил тот же результат.

1 Ответ

0 голосов
/ 12 мая 2020

Решение выглядит немного странно

Не используйте ключ аутентификации APN, а вместо этого используйте сертификаты p12

Я проверил прямые APNS pu sh уведомления ( без firebase) используя 2 метода APNS ключ авторизации и сертификаты p12, и я могу подтвердить, что ключ авторизации не работал для iOS 13

Когда я использовал сертификаты p12, он работал как для APNS (прямой), так и с использованием firebase

enter image description here

...