按主题iOS的FCM推送通知

时间:2020-04-05 12:19:20

标签: ios swift firebase push-notification firebase-cloud-messaging

我正在尝试使用Firebase FCM控制台向特定主题的所有订阅者发送通知。问题是我仅在一台设备上收到通知,这是我在应用程序委托中的代码:

      FirebaseApp.configure()
      let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
      UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: {_, _ in })

    application.registerForRemoteNotifications()
    UNUserNotificationCenter.current().delegate = self
    Messaging.messaging().delegate = self
    return true
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {

    let dataDict:[String: String] = ["token": fcmToken]
    NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
    InstanceID.instanceID().instanceID { (result, error) in
      if let error = error {
        print("Error fetching remote instance ID: \(error)")
      } else if let result = result {
        print("Remote instance ID token: \(result.token)")
        DispatchQueue.main.async {
            Messaging.messaging().subscribe(toTopic: "Athan") { error in
              print("Subscribed to athan topic")
            }
        }

      }
    }
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }
  print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
      if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
      }
        if let message : [String : Any] = userInfo["aps"] as? [String : Any]{
            print(message,"test",userInfo)
            if let messageAlert : [String : Any] = message["alert"] as? [String : Any]{
                if let lBody : String = messageAlert["body"] as? String, let lTitle : String = messageAlert["title"] as? String{
                    print (lBody,lTitle)
                    if lTitle == "Notification" && lBody.contains("Your daily verse is here") {
                    }
                }

            }
        }
      let sName = userInfo["sound"] as? String
        if sName == "athan.caf"{
            let url = URL(fileURLWithPath: "\(Bundle.main.resourcePath!)/\(sName ?? "")")
            audioPlayer = try? AVAudioPlayer(contentsOf: url)
            audioPlayer?.numberOfLoops = 0
            audioPlayer?.play()
        }
      completionHandler(UIBackgroundFetchResult.newData)
    }

如何确保主题的所有订阅者都收到这些推送通知?我需要使用设备令牌并将其发送到Firebase FCM控制台吗?

0 个答案:

没有答案