首页 > 解决方案 > 如何在 iOS 中将 Firebase 推送通知从设备发送到设备

问题描述

我成功集成了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()
    }
}

标签: swiftfirebasefirebase-cloud-messaging

解决方案


如果要从设备发送推送通知到设备,则必须使用 Firebase Cloud 功能。如果按照示例代码来实现,并不难。在此处查看文档,您可以从他们的github 存储库中查看示例。


推荐阅读