Не удается получить доступ к PayLoad push-уведомлений в консоли XCode - PullRequest
0 голосов
/ 31 января 2019

Я пытаюсь отправить уведомление на устройство iOS, я использую FCM, я получаю уведомление на своем устройстве, но я не получаю полезную нагрузку в консоли XCode, и я хочу получить доступ к полезной нагрузке, потому что япланирует хранить уведомления в UITableView как историю, потому что это приложение оповещений.

Моя полезная нагрузка:

{"aps": {"alert": {"title":"Привет", "тело": "Как дела?"}, "badge": 0, "sound": "default", "data": "Это тест!"}}

//  AppDelegate.swift
//  P.T.S
//
//  Created by Hussein AlBehary on 1/19/19.
//  Copyright © 2019 Hussein AlBehary. All rights reserved.
//

import UIKit
import Firebase
import UserNotifications

@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.
        debugPrint("didFinishLaunchingWithOptions")

        // Enable Push Notifications
        Messaging.messaging().delegate = self
        Messaging.messaging().shouldEstablishDirectChannel = true

        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()
        FirebaseApp.configure()

        return true
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
    {
        Messaging.messaging().appDidReceiveMessage(userInfo)
        if let messageID = userInfo[gcmMessageIDKey]
        {
            print("Message ID: \(messageID)")
            debugPrint("Message ID: \(messageID)")
        }else if let myData = userInfo["data"] as? [String: AnyObject] {
            print(myData)
        }
        // Print full message.
        debugPrint(userInfo)
        completionHandler(UIBackgroundFetchResult.newData)
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
    {
        debugPrint("didRegisterForRemoteNotificationsWithDeviceToken: DATA")
        let token = String(format: "%@", deviceToken as CVarArg)
        debugPrint("*** deviceToken: \(token)")
        let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
        debugPrint("deviceTokenString: \(deviceTokenString)")
        Messaging.messaging().apnsToken = deviceToken
        //        debugPrint("Firebase Token:",InstanceID.instanceID().token() as Any)
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Unable to register for remote notifications: \(error.localizedDescription)")
    }


}

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

        //Handle the notification ON APP
        Messaging.messaging().appDidReceiveMessage(notification.request.content.userInfo)
        completionHandler([.sound,.alert,.badge])
    }

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

        //Handle the notification ON BACKGROUND
        Messaging.messaging().appDidReceiveMessage(response.notification.request.content.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)")
        InstanceID.instanceID().instanceID
            {
                (result, error) in
                if let error = error
                {
                    debugPrint("Error fetching remote instange ID: \(error)")
                }
                else if let result = result
                {
                    debugPrint("Remote instance ID token: \(result.token)")
                }
        }
        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)")
        debugPrint("Received data message: \(remoteMessage.appData)")
    }
    // [END ios_10_data_message]
}

Хотя проблема связана с приборной панелью FCM, поэтому я попробовал приложение MacOS под названием Pusher и добавил свою полезную нагрузку, но с тем же результатом я получаю уведомление на своем устройствено не в xcode.

...