FCM: сообщение отправлено, но не получено - PullRequest
0 голосов
/ 23 сентября 2018

пытался решить это сам.провел как час или около того до сих пор безрезультатно.

Получил старый код предыдущего проекта относительно FCM.однако код был и все еще работает над своим приложением.хотя мне удалось перенести код в мой новый проект.но это не сработает.

Теперь я знаю, что APN странные и сложные.но для меня это скорее запоминающаяся ситуация.

То, что я сделал: - загрузил свой личный файл .p12 в мой проект firebase - включил "Push-уведомления" в возможностях приложения - импортировал и использовал инфраструктуру пользовательских уведомлений на appdelegate.swift

Вот как мой AppDelegate выглядит так:

import UIKit
import Firebase
import FirebaseFirestore
import StoreKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {

    var window: UIWindow?


    override init() {
        super.init()
            FirebaseApp.configure()
            // not really needed unless you really need it FIRDatabase.database().persistenceEnabled = true
    }
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        Auth.auth().signInAnonymously() { (authResult, error) in
            // ...
            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()
        }





        Messaging.messaging().delegate = self
        UIApplication.shared.statusBarStyle = .default



        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let viewController = mainStoryboard.instantiateViewController(withIdentifier: "gateway") as! gatewayViewController
       window!.rootViewController = viewController

        return true
    }

    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.
    }
    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)
    }

Хорошо, с этим кодом вы получаете устройства Жетон регистрации Firebase , я скопировал свой код и использовал его в Облачные функции чтобы отправить тестовое сообщение, вот как выглядит мой CF:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

 exports.helloWorld = functions.https.onRequest((request, response) => {

var registrationToken = 'f8fWx_sANVM:APA91bEd46drxiBvHLZd5YKVClQr91oubzJKOyXE1LNgxOsi3ihUw31yEJL6prHKm-A83B1N1sr2GOff3P9tUsRNhCpG7_VMRlDUDfthIcwkDUgzKPV5NZtlo6pcpxsvD9ZgYlPqibNp';

 var payload = {
      notification: {
        title: "just published new Word",
        body: "Hii",
      }
    };


// registration token.
admin.messaging().sendToDevice(registrationToken, payload)
  .then(function(response) {
    // See the MessagingDevicesResponse reference documentation for
    // the contents of response.
    return console.log("Successfully sent message:", response);

  })
  .catch(function(error) {
    console.log("Error sending message:", error);
  }); 



 });

Хорошо, пока после нажатия на helloWorld url, моя консоль получает следующее:

Успешно отправлено сообщение: {результаты: [{messageId: '0: 1537714204565821% b3b8835bb3b8835b'}], canonicalRegistrationTokenCount: 0, failCount: 0, successCount: 1, multicastId: 8154206809408282000}

выполнение * взято * выполнение * 2660002 мс, закончено со статусом: «тайм-аут»

В прошлый раз в моем предыдущем проекте это заняло 20 мс в лучшем виде.Я до сих пор не могу понять это.Ваша помощь очень ценится

1 Ответ

0 голосов
/ 23 сентября 2018

Вы используете облачную функцию, запускаемую по протоколу HTTP (S), что означает, что ваш код должен отправить ответ.Поскольку ваш код этого не делает, функция выполняется в течение 60 с, а затем завершается средой Cloud Functions.Это означает, что вы платите за больше времени, чем вам на самом деле нужно, поэтому вы захотите это исправить.

Например:

// registration token.
admin.messaging().sendToDevice(registrationToken, payload)
  .then(function(response) {
    // See the MessagingDevicesResponse reference documentation for
    // the contents of response.
    //return console.log("Successfully sent message:", response);
    res.status(200).send(response);
  })
  .catch(function(error) {
    console.log("Error sending message:", error);
  }); 

Это избавит от сообщения в журналах облачных функций и гарантирует, что вы платите только за то время, которое вам действительно нужно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...