首页 > 解决方案 > iOS firebase 通知在后台不起作用

问题描述

您好,我调用了 Firebase 函数,如果应用程序已关闭或在后台,我会收到推送通知,但在此通知上还有其他数据,请参阅 JS 脚本。我的问题是我想在 Usersdefault 中写入这些数据但没有调用任何方法?!我不知道为什么。如果该应用程序在前台,则一切正常。在 Plist 我添加了 "FirebaseAppDelegateProxyEnabled" = NO JS 功能:

let title = "Test";
    let body =  "TestBody"; 
   
    const message = {
        notification: { title: title, body: body },
        apns: { 
            payload: { 
                aps: { 
                    "content_available" : 1,
                    sound: 'default', 
                    badge: 4,
                } 
            } 
        }, 
        token: "e0BURkoe0EAq....CIscNukai",
        data: { 
            event: "custom1", 
            type: "CustomTest",
        }
    }

Appdelegate.swift 查看块:

if ( userInfo["type"] as! String == "CustomTest" ) {
            ###########
            ###########
            DO SOMETHING

        }

源代码

import UIKit
import Firebase
import GooglePlaces
//import GoogleMaps

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var db:Firestore!
    let gcmMessageIDKey = "gcm.Message_ID"
    let defaults = UserDefaults.standard
    var disabledChats = [String]()
    
   

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
         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()
        UNUserNotificationCenter.current().delegate = self
        
        Messaging.messaging().delegate = self
 
        return true
    }


    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
      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) {
 
      // Print full message.
        print(userInfo)
        
        completionHandler(.newData)
    }
    
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
        let token = tokenParts.joined()
        Messaging.messaging().apnsToken = deviceToken
        //UIApplication.shared.applicationIconBadgeNumber = 5
        print("Device Token: \(token)")
        print("Device Token1: \(deviceToken)")
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
      print("Failed to register: \(error)")
    }

   
}




@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)")
        }
        

        
        if ( userInfo["type"] as! String == "CustomTest" ) {
            ###########
            ###########
            DO SOMETHING
            
        }
        
        completionHandler([[.alert, .sound]])

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

        // With swizzling disabled you must let Messaging know about the message, for Analytics
        // Messaging.messaging().appDidReceiveMessage(userInfo)
        // Print full message.
        print(userInfo)

        completionHandler()
      }
  
}



extension AppDelegate : MessagingDelegate {
  // [START refresh_token]
  func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
    print("Firebase registration token: \(String(describing: 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]
}

标签: swiftfirebasefirebase-cloud-messaging

解决方案


您需要更改通知负载。您需要使用以下有效负载进行 IOS 通知。

aps:{警报:{标题:“标题”,正文:“正文”,名称:“名称”,事件:“custom1”,类型:“CustomTest”}}


推荐阅读