Уведомления не принимаются на iPhone с помощью быстрой передачи из облачной службы Firebase - PullRequest
0 голосов
/ 03 июля 2019

Я хочу отправлять уведомления из моего приложения в другое приложение, используя облачные сообщения Firebase. Поэтому я использовал этот метод retrieveFCMToken (forSenderID: senderid) для этого процесса. Я добавляю фрагмент кода в мой делегат приложения:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("APNs token retrieved: \(deviceToken)")
    Messaging.messaging().apnsToken = deviceToken

    let senderid = "<YOUR SENDER ID>"
    Messaging.messaging().retrieveFCMToken(forSenderID: senderid) {(message,Error) in  
        print("message",message!)
    }
}

и это мой делегат приложения:

import UIKit
import UserNotifications

import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    let gcmMessageIDKey = "gcm.message_id"

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

        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
    }

    // [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) {
        print("APNs token retrieved: \(deviceToken)")
        Messaging.messaging().apnsToken = deviceToken

        //Code for sending to other sender ID
        let senderid = "594023696508"
        Messaging.messaging().retrieveFCMToken(forSenderID: senderid) {(message,Error) in  // here i am generating the token for other sender id project
            print("message",message!)
        }
    }
}

// [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]
        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)")
    }
    // [END ios_10_data_message]
}

Я следовал этому сценарию: у меня есть два приложения, это "A" и "B". Я хочу отправлять уведомления из приложения "A" в приложение "B". Поэтому я поместил идентификатор отправителя приложения A в файл делегата приложения B и сгенерировал маркер регистрации для приложения A с помощью приложения B. Поэтому я поместил сгенерированный маркер регистрации в консоль облачных сообщений Firebase приложения A при отправке уведомления в приложение B Но приложение Б не получает уведомления. Как решить эту ошибку? Я загрузил действительный ключ авторизации APN в базу данных обоих приложений в облачной службе Firebase.

Ответы [ 2 ]

0 голосов
/ 03 июля 2019

Метод расширения, который вы написали, в порядке. Но, пожалуйста, проверьте перечисленные ниже вещи с консоли FCM, чтобы найти проблему с неполучением уведомлений.

Для другого приложения, на которое вы ссылаетесь, вам необходимо добавить идентификатор этого пакета в FCM и сгенерировать файл google info.plist для этого конкретного приложения. Затем вы должны выполнить шаги, чтобы проверить уведомления в вашем приложении.

Что проверить на наличие токена FCM в iOS

  1. Пожалуйста, проверьте, что на console.firebase.com ваше приложение имеет правильный файл p.12 в настройках приложения.

  2. Сервер установил правильный ключ API сервера, который отображается в настройках приложения console.firebase.com.

  3. Файл Google info.plist необходимо загрузить и добавить в проект.

Надеюсь, это поможет вам.

0 голосов
/ 03 июля 2019

A & B - это два ОТДЕЛЬНЫХ ПРИЛОЖЕНИЯ, поэтому один токен FCM недействителен для другого.Каждое приложение генерирует уникальный токен, который относится только к его проекту Firebase.Чтобы отправлять и получать уведомления от А до Б или от В до А, необходимо настроить оба проекта Firebase в каждом приложении, а затем получить соответствующий токен FCM.После этого вы сможете отправлять и получать уведомления

...