微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

两次接收推送通知有效载荷数据

如何解决两次接收推送通知有效载荷数据

每当我从Firebase控制台发送推送通知时,它都会发送一次,但是当我以编程方式发送时,设备会收到两次。我正在使用实时Firebase日期和云功能。 这是我的AppDelegate.swift

@UIApplicationMain

AppDelegate类:UIResponder,UIApplicationDelegate { var window:UIWindow? // ------------------------------------------------ -------------------------------------------------- -------------------------------------------------- //

lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "mChat")
    container.loadPersistentStores(completionHandler: {
        (storeDescription,error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error),\(error.userInfo)")
        }
    })
    return container
}()

// ---------------------------------------------------------------------------------------------------------------------------------------------------- //

func saveContext() {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do{
            try context.save()
        }catch{
            let error = error as NSError
            fatalError("Unresolved error \(error),\(error.userInfo)")
        }
    }
}

// ---------------------------------------------------------------------------------------------------------------------------------------------------- //

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

 FirebaseApp.configure()
 
 
 self.registerForPushNotifications(application)
         return true
}

// ---------------------------------------------------------------------------------------------------------------------------------------------------- //

// MARK: UIScenesession Lifecycle

func application(_ application: UIApplication,configurationForConnecting connectingScenesession: UIScenesession,options: UIScene.Connectionoptions) -> UISceneConfiguration {
    return UISceneConfiguration(name: "Default Configuration",sessionRole: connectingScenesession.role)
}

// ---------------------------------------------------------------------------------------------------------------------------------------------------- //

func application(_ application: UIApplication,diddiscardScenesessions scenesessions: Set<UIScenesession>) {
    guard let userId = CurrentUser.uid else { return }
    let userRef = Database.database().reference().child("userActions").child(userId)
    userRef.removeValue()
}

// ---------------------------------------------------------------------------------------------------------------------------------------------------- //

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

}

    then my appdelegate+notifications.swift
import Foundation
import UIKit
import UserNotifications
import Firebase
import FirebaseMessaging

extension AppDelegate: UNUserNotificationCenterDelegate {
    
    func registerForPushNotifications(_ application: UIApplication){
        
        if #available(iOS 10.0,*){
            
            UNUserNotificationCenter.current().delegate = self
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound],completionHandler: { ( _,_ ) in})
            
        } else {
            
            let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert,categories: nil)
            application.registerUserNotificationSettings(settings)
            
        }
        
        application.registerForRemoteNotifications()
        
    }
    
    func application(_ application: UIApplication,didRegisterForRemoteNotificationsWithDevicetoken devicetoken: Data) {
        Messaging.messaging().subscribe(toTopic: "ALL")
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter,willPresent notification: UNNotification,withCompletionHandler completionHandler: @escaping (UNNotificationPresentationoptions) -> Void){
        processNotification(notification)
        completionHandler(.badge)
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter,didReceive response: UNNotificationResponse,withCompletionHandler completionHandler: @escaping () -> Void){
        processNotification(response.notification)
        completionHandler()
    }
    
    private func processNotification(_ notification: UNNotification) {
        //FUTURO ERIC
    }
    
}
//

这是我的云功能

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

exports.newMessage = functions.database.ref('messages/{uid}/{friendId}/{messageId}').onWrite((event,context) => {

    const discussionId = context.params.uid;
    const messageId = context.params.messageId;

    const message = event.after.val();

   

    var message_value = message.sender;
var messagebody = message.message;
    const setNewMessagePromise = admin.database().ref(`/users/${message_value}/name`).once('value').then(snapshot => {
const messageContent = snapshot.val();   
 const payload = {
        notification: {
            title: messageContent,body: messagebody,sound: 'default'
        }
    } 
 const options = {
            priority: 'high',timetoLive: 60 * 60 * 24
        };   
const sendMessagePromise = admin.messaging().sendToTopic("ALL",payload,options);
  return Promise.all([setNewMessagePromise,sendMessagePromise]);   
 }); 

});

需要帮助,为什么我两次收到通知

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。