首页 > 解决方案 > iOS 应用无法接收来自 Firebase 的通知

问题描述

我将 Firebase Cloud 功能与 Firebase Cloud Messaging 一起使用。但我没有在我的设备上收到任何通知。

这是我的 index.ts:

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();


exports.sendNotificationOnInvitation = functions.firestore.document("invitations/{invID}").onWrite(async (event) => {
  const eventID = event.after.get("eventID");
  const theStatus = event.after.get("status");
  console.log("The event id is " + eventID);
  const invitedBy = event.after.get("invitedBy");
  const inviteeID = event.after.get("inviteeID");

  const fcmDoc = await admin.firestore().collection("fcmTokens").doc(inviteeID).get();
  //const fcmSnap = fcmDoc.data();
  const theFCM = fcmDoc.get("token"); //
  console.log("The FCM is: " + theFCM);

  console.log("The status is "+ theStatus);


  const eventDoc = await admin.firestore().collection("privateEvents").doc(eventID).get();
  const eventName = eventDoc.get("eventName"); //
  console.log("The event Name is "+ eventName);
  const eventDate = eventDoc.get("eventDate");

  if(theStatus === "pending"){
      const message = {
          notification: {
              title: "Party!",
              body: "The party is " + eventName,
          }
      }

      const response = await admin.messaging().sendToDevice(theFCM, message);
      console.log(response);
      //console.log("The FCM is " + theFCM);
  }

});

exports.sendNotificationOnConfirmation = functions.firestore.document("invitations/{invID}").onUpdate(async (event) => {
  const theStatus = event.after.get("status");
  const eventID = event.after.get("eventID");
  console.log("The event id is " + eventID);
  const invitedBy = event.after.get("invitedBy");
  const inviteeID = event.after.get("inviteeID");

  const fcmDoc = await admin.firestore().collection("fcmTokens").doc(inviteeID).get();
  const theFCM = fcmDoc.get("token"); //
  console.log("The FCM is: " + theFCM);

  const eventDoc = await admin.firestore().collection("privateEvents").doc(eventID).get();
  const eventName = eventDoc.get("eventName"); //
  console.log("The event Name is "+ eventName);
  const eventDate = eventDoc.get("eventDate");

  console.log("The status is "+ theStatus);

  if (theStatus === "confirmed") {
    const message = {
      notification: {
        title: "Welcome!",
        body: "You're confirmed",
      }
    };

    const response = await admin.messaging().sendToDevice(theFCM, message);
    console.log(response);
    
  }
});

这是我的 AppDelegate.swift:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    static var theFcmToken: String?

    var window: UIWindow?


    override init() {
       super.init()
       FirebaseApp.configure()
    }
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        //FirebaseApp.configure()
        
        
        IQKeyboardManager.shared().isEnabled = 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()
        Messaging.messaging().delegate = self
        //FirebaseApp.configure()
        
        
        
 

        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:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "Champagne_Supernova")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                 
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

   
}

extension AppDelegate: MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        print("Messaging running")
        messaging.token { token, _ in
            guard let token = token else {
                return
            }
            print("Token: \(token)")
            //save token to static var which will be accessed when user signs in.
            Self.theFcmToken = token

            
        }
    }
}

@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 full message.
        print(userInfo)
        
        // Change this to your preferred presentation option
        completionHandler([[.alert, .sound]])
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        
        // ...
        
        // With swizzling disabled you must let Messaging know about the message, for Analytics
        // Messaging.messaging().appDidReceiveMessage(userInfo)
        
        // Print full message.
        print(userInfo)
        
        completionHandler()
    }
}

我一直在使用 Firestore 集合来触发这两个函数,它们确实被触发并且函数正确运行和执行(根据 Firebase 控制台上的日志),但设备上没有任何反应。控制台上的日志显示 Function execution took 205 ms, finished with status: 'ok' 我相信我已经按照 Firebase 文档的要求完成了所有工作。

知道问题可能出在哪里吗?因为我一直在绞尽脑汁试图找到错误,但我找不到任何东西。谢谢你。

标签: iosswiftfirebasegoogle-cloud-functionsfirebase-cloud-messaging

解决方案


推荐阅读