Pepe Ocaña
Pepe Ocaña

Reputation: 75

Ionic 4 + Firebase - Send Notification User Chat App

I'm building a Chat App with Ionic 4 + Firebase and I would like to send a notification to the device of the user when he receives a new message, even if the app is not running.

I've been googleing a lot and there are different ways, FCM, onesignal (I dont like them since I found that the service is free but they sell the data of your app to third partiy companies..) , etc... but a lot of the answers are like 2-3 years old so I dont want to start building something and then realize that doesnt work with the latest IOS or Android versions...

I dont want to send notifications to all the users like the most of the FCM tutorials do, I'll try to do this in the future if I have to, now I only want to create a cloud function that gets triggered when something has been added to the firebase data path /messages/ and send a notification to the user.

Last thing, can this be tested without building the actual app? I still in developing phase, I test everything with ionic serve lab and the App Ionic DevApp that allows me to test cordova plugins for native features, all the tutorials for notifications for FCM they explain how to register the app, so the app has to be actually built before. Is it possible to test it directly with the Ionic DevApp and ionic serve?

Thanks!

Upvotes: 1

Views: 603

Answers (1)

Ravi Ramya
Ravi Ramya

Reputation: 11

sendPushNotification() {
    const headers = new HttpHeaders({
      "Content-Type": "application/json",
      Authorization: "firebase_serverkey"
    });

    console.log("Headers", headers);
    let body = {
      "notification": {
        "title": "User",
        "body": "New message",
        "sound": "default",
        "click_action": "FCM_PLUGIN_ACTIVITY",
        "icon": "fcm_push_icon"
      },
      "data": {
        "landing_page": "second",
        "price": "$3,000.00"
      },
      "to": this.activatedRoute.snapshot.paramMap.get('token'),
      "priority": "high",
      "restricted_package_name": ""
    }

    this.http.post('https://fcm.googleapis.com/fcm/send', JSON.stringify(body), { headers: headers })
      .subscribe(res => {
        console.log("data from notification", res)
      })
  }

Upvotes: 1

Related Questions