Swift 5 - 无法通过 FCM 接收推送通知

Posted

技术标签:

【中文标题】Swift 5 - 无法通过 FCM 接收推送通知【英文标题】:Swift 5 - Not able to receive Push Notification through FCM 【发布时间】:2020-09-11 07:07:29 【问题描述】:

我无法收到推送通知,这是我的有效负载


  "to": "erOZW7CN....(fcm token)",
  "data": 
    "body": "Incoming-Call",
    "title": "AppName",
    "type": "incoming-call",
    "number": "0212222222"
  ,
  "aps": 
    "alert": 
      "title": "AppName",
      "body": "Incoming-Call"
    
  

data 部分适用于 android。当我使用notification 而不是aps 时,它可以工作,但Android 端会出现问题。所以我需要使用aps 来检测请求。我做了很多研究,但找不到任何解决方案。

这是我的 AppDelegate

import UIKit
import CoreData
import Firebase
import Network


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


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool 
        // Override point for customization after application launch.
        
        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()
        Messaging.messaging().delegate = self
        
        return true
    
    

    
    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration 
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    

    @available(iOS 13.0, *)
    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) 

    
    
    lazy var persistentContainer: NSPersistentContainer = 
        let container = NSPersistentContainer(name: "Database")
        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 nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            
        
    

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) 
        Messaging.messaging().apnsToken = deviceToken
    
    

    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)
        UserDefaults.standard.set(fcmToken, forKey: "fcmToken")
    
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) 
        print("Push Received: \(userInfo)")
        //TODO: CALLKIT DETECT
    

注意:我正在从 Postman 发送请求

在这里找到解决方案会很棒。谢谢。

【问题讨论】:

也许这会有所帮助***.com/questions/37358462/… “不能”是什么意思? @HarisD。这是安卓版的。 好的。我认为您可以尝试使用github.com/KnuffApp/Knuff 进行调试。也许会给你一些额外的信息。可能是这样:-您的令牌是为产品生成的,但您正在尝试将 PN 发送到沙盒 APN,反之亦然。 - 可能是证书问题。 @HarisD。 knuff 发送到设备令牌,我需要发送通知 fcm 令牌并使用“aps”令牌检测它 【参考方案1】:

通过 FCM 或 APNS 发送推送通知时,生成您的有效负载,如下所示。

基本负载:iOS 和 Android(通过 FCM 发送)


  "message": 
      "notification": 
        "body": "YOUR MESSAGE BODY HERE",
        "title": "YOUR MESSAGE TITLE HERE"
      
  

基本负载:iOS(通过 APNS 发送)


  "aps": 
    "alert": 
      "body": "YOUR MESSAGE BODY HERE",
      "title": "YOUR MESSAGE TITLE HERE"
    
  

注意:

didReceiveRemoteNotification 函数中,您将收到符合 iOS 风格的有效负载。

【讨论】:

"data" 部分适用于 android,当我使用 "notification" 而不是 "aps" 时它可以工作,但 android 端会出现问题,所以我需要使用 "aps" 来检测请求 @Oğuz 看起来您确实混淆了两个不同的系统。 MilanPanchal 展示了设置通知的正确方法。我认为您应该花一些时间阅读来自FCM 和Apple 的关于推送通知如何工作的文档。在 FCM 中,Data仅适用于 Android,它用于发送应用使用的有效负载。

以上是关于Swift 5 - 无法通过 FCM 接收推送通知的主要内容,如果未能解决你的问题,请参考以下文章

IONIC FCM推送通知ios,无法接收

无法接收 FCM 推送通知 IOS - 目标 C

无法接收 iOS 的 FCM 推送通知

如何在接收基于 Flutter 构建的 FCM 推送通知时修复应用程序崩溃

如果应用程序终止,则未收到 iOS FCM 推送通知

应用程序被杀死时无法接收推送解析 FCM