0

I integrated firebase successfully. when I send notification using cloud messaging from firebase site just for a test purpose it is received by device. but in my app I need to send notification from one device to another device using firebase.. how to implement that. Swift 4, Xcode 10 here is some code:

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()
    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Rj19
  • 305
  • 1
  • 6
  • 20
  • Sending a message **to** a device through FCM requires that you specify the so-called FCM server key. As its name implies, this key should only be user on a server or otherwise trusted environment, since it allows the holder to send any message to any and all users of your app. See https://stackoverflow.com/q/37655269, https://stackoverflow.com/q/37634046, and https://stackoverflow.com/a/37993724 (for Android, but the same applies to iOS). – Frank van Puffelen Sep 16 '19 at 12:25

1 Answers1

0

If you want to send push notifications from device to device you will have to use Firebase Cloud functions. It's not difficult to implement if you follow the sample code. Check the docs here and you can check samples from their github repo.

Mussa Charles
  • 4,014
  • 2
  • 29
  • 24