swift - 如何在 iOS 中从设备到设备发送 Firebase 推送通知

标签 swift firebase firebase-cloud-messaging

我成功集成了 firebase。当我出于测试目的使用 Firebase 站点的云消息发送通知时,设备会收到该通知。但在我的应用程序中,我需要使用 firebase 将通知从一台设备发送到另一台设备。如何实现。 swift 4、Xcode 10 这是一些代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
       formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

         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)
        }
         Messaging.messaging().delegate = self

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)")
                self.deviceTokenString = result.token as NSString
            }
        }
        application.registerForRemoteNotifications()

        registerForPushNotifications()
}


  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {


       }

 private func application(application: UIApplication,  didReceiveRemoteNotification userInfo: [NSObject : AnyObject],  fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

     print("Recived: \(userInfo)")
   completionHandler(.newData)

    }

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


@available(iOS 10.0, *)
extension AppDelegate : MessagingDelegate {
    // [START refresh_token]
    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)

    }
    Messaging.messaging().shouldEstablishDirectChannel to true.
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Received data message: \(remoteMessage.appData)")
    }

}
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {


    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo

        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }


        print(userInfo)


        completionHandler([.alert])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo

        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }


        print(userInfo)

        completionHandler()
    }
}

最佳答案

如果您想在设备之间发送推送通知,则必须使用 Firebase Cloud 功能。如果您按照示例代码进行操作,实现起来并不困难。检查文档 here您可以从他们的 github 检查样本 repo 。

关于swift - 如何在 iOS 中从设备到设备发送 Firebase 推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57955937/

相关文章:

javascript - 在 Firestore 中组合 orderBy 和 where 子句

java - 无法实例化服务 firebase.MyFirebaseInstanceIdService :java. lang.ClassNotFoundException :Didnt find class . MyFirebaseInstanceIdService

swift - Firebase 计划推送通知

swift - 使用 Storyboard 时如何将选择器添加到菜单项

javascript - 使页面只有在登录后才能访问 - Firebase Web

swift - "Missing required entitlement"用于 NFCTagReaderSession

java - 如何获取Firestore的特定文档ID?

android - 第一个 cURL 请求验证 GCM api key

ios - [NSObject : AnyObject] ?' does not have a member named ' subscript' error in Xcode 6 beta 6

ios - Twitter API 趋势 Swift