Как запустить функцию, не показывая push-сообщение при его отправке? - PullRequest
2 голосов
/ 01 ноября 2019

У меня есть проблема, которую нужно решить с помощью push-сообщения. Если я отправлю push-сообщение на Firebase, я получу его хорошо, и я увижу сообщение хорошо.

И когда я нажимаю на push-сообщение, выполняется функция userNotificationCenter в файле AppDelegate и выполняется список действий в функции.

Можно ли выполнить функциюбез получения конкретного сообщения и отображения сообщения?

Где я в данный момент получаю и обрабатываю push-сообщения.

    @available(iOS 10, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let data = response.notification.request.content.userInfo

        guard
            let push = data[AnyHashable("push")] as? String,
            let getdata = data[AnyHashable("getdata")] as? String,
            let pushdata = data[AnyHashable("pushdata")] as? String
            else {
                print("it's not good data")
                return
        }
        print(push)
        print(getdata)
        print(pushdata)
}

   @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        completionHandler([.alert, .badge, .sound])
    }

Моя цель - выполнить функцию, не отображая push-сообщение дляпользователь при отправке конкретного сообщения (Ex: push = "noShowPush") из Firebase.

РЕДАКТИРОВАТЬ

Я пытался "content_available": true, но получить журнал 6.10.0 - [Firebase/Messaging][I-FCM002019] FIRMessaging received data-message, but FIRMessagingDelegate's-messaging:didReceiveMessage: not implemented

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

        self.window = UIWindow(frame: UIScreen.main.bounds)
        // Override point for customization after application launch.
        //create the notificationCenter
        Messaging.messaging().delegate = self
        FirebaseApp.configure()

        //Register App For Push Notification
        //        self.registerAppForPushNotificaition()
        let center = UNUserNotificationCenter.current()
        let inviteCategory = UNNotificationCategory(identifier: "Notification", actions: [], intentIdentifiers: [], options: UNNotificationCategoryOptions.customDismissAction)
        let categories = NSSet(objects: inviteCategory)

        center.delegate = self
        center.setNotificationCategories(categories as! Set<UNNotificationCategory>)
        DispatchQueue.main.async(execute: {
            UIApplication.shared.registerForRemoteNotifications()
        })
        application.registerForRemoteNotifications()
        self.updateAppViewUI()
        self.window?.makeKeyAndVisible()
        return true
 }
   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) {
        Messaging.messaging().appDidReceiveMessage(userInfo)
        if Auth.auth().canHandleNotification(userInfo) {
            completionHandler(UIBackgroundFetchResult.noData)
            return
        }
        completionHandler(UIBackgroundFetchResult.newData)
    }

У меня естьуже Messaging.messaging().delegate = self.

Журналы в Firebase предупреждают вас, чтобы установить FirebaseAppDelegateProxyEnabled на No, поэтому я добавил к Info.list. enter image description here

и Firebase журнал изменен [Firebase/Core][I-COR000003] The default Firebase app has not yet been configured. Add '[FIRApp configure];' ('FirebaseApp.configure()' in Swift) to your application initialization. Read more:

Вещи, которые я пересматриваю, идут правильно?

Как я могуэто решение?

1 Ответ

1 голос
/ 04 ноября 2019

Я решил проблему. Вот порядок, в котором я работал:

  1. Пишите, когда отправляете push "content_available": true". И не включайте title и body.
  2. И когда я получил эти журналы ошибок, 6.10.0 - [Firebase/Messaging][I-FCM002019] FIRMessaging received data-message, but FIRMessagingDelegate's-messaging:didReceiveMessage: not implemented
  3. Журналы в Firebase попросили вас установитьFirebaseAppDelegateProxyEnabled Нет, поэтому я добавил к Info.list.

    ㅎㅎ

  4. и изменил порядок выполненияфункция.

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
        FirebaseApp.configure() // Let it run first.
        Messaging.messaging().delegate = self
        self.window = UIWindow(frame: UIScreen.main.bounds)
        ...
    
  5. И я установил 'Firebase/Analytics' на стручок. pod 'Firebase/Analytics'

  6. и унаследовал MessagingDelegate и реализовал функцию Messaging.

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("fcmToken \(fcmToken)")
    }
    
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        Log.Info("remort \(remoteMessage.appData)")
        let userInfo = remoteMessage.appData
    }
    

Эта конфигурация позволяет получатьPush-данные сообщения в функцию messaging при отправке push-сообщения. Это push-сообщение со значением contentAvailable, равным True, без title и body.

.
...