Send Push Notifications with FCM using C# (Topics & Tokens)
Вставка
- Опубліковано 22 лип 2024
- We've already implemented receiving push notifications on iOS and Android with Xamarin.Forms, now it's time to send push notifications from code. In this video we will learn how to send push notifications through FCM using C# and send notifications to device tokens, but also to topics.
💝 Join this channel to get access to perks:
ua-cam.com/users/GeraldVerslui...
🛑 Don't forget to subscribe to my channel for more amazing content: ua-cam.com/users/GeraldVerslui...
🐦 Follow me on Twitter: / jfversluis
🤝 Join the Discord server: / discord
🔗 Links
Sample App Repo: github.com/jfversluis/XFFCMPu...
Plugin Repo: github.com/firebase/firebase-...
Android Video: • Implement Push Notific...
iOS Video: • Implement Push Notific...
⏱ Timestamps
00:00 - Intro
00:17 - Inspect End Result
01:02 - Hold Up! Shoutout Time!
01:48 - Setup Firebase Service Account
04:27 - Sample App Overview
05:37 - Add Send Push Notifications Project
07:15 - Install FirebaseAdmin NuGet Plugin
11:47 - Implement Sending Notifications to Token
14:13 - Sample Send Notification From Code
15:36 - Send Notifications To Topics
16:25 - Subscribe to Topic from App
18:06 - Implement Sending Notifications To Topic
20:02 - Outro
🎥 Video edited with Camtasia (ref): techsmith.z6rjha.net/AJoeD
🙋♂️ Also find my...
Twitter: / jfversluis
Blog: blog.verslu.is
Twitch: / jfversluis
All the rest: jfversluis.dev
#XamarinForms #PushNotifications #FCM #Xamarin #PushNotifications #Firebase #FirebaseCloudMessaging #iOS #Android - Наука та технологія
This video should be the go-to video for anyone who wants to understand the push notification through C#
Thank you a million tutor! You have created a great work
Thank you so much!
Last year I spent hours trying to figure you how to implement push notification. You are the man!!!!
Woohoo! Yeah it can be a chore... I think it helps to just see how someone else does it, repeat the steps and that makes it stick better for you as well. Glad it helped, thanks!
I spent 4 hours scrolling through microsoft documentation, couldn't even make it compile afterwards because everything was outdated. I watched your 2 videos, and it took me less than an hour to set up a client-server communication. Thanks man!
Amazing, thank you so much for taking the time to let me know! This is hard stuff, and this wasn't easy to create. Glad it is helping people :)
The much painful part of coding is each time you struggle fixing bugs or finding solutions. Each time I search online and came across your videos I know that I finally found the solution and that my life is saved again and again...
You may not know how much helpful you are, please know that you are the most helpful guy I found online during my last 15 years of coding!
Thanks a billion
Wowowow you made my week! That is so very nice of you to say. Thank you for that. These are exactly the types of things that keep me going. Trying to help out wherever I can. Glad to hear that is working out, even long after I have posted this initially. Thank you my friend!
Be a member of this guy's channel to properly thank and support him for his great videos like this.
I approve of this message! Thanks for your support 😄❤️
@Gerald Versluis - I would LOVE to see a series on "So your app works great; now what??"
This would be a series of videos explaining in detail how to take all the steps necessary to launch on the App Store or the Play Store. I STILL find the tokens and keys that Apple forces you to have (even to deploy to your own phone), and all the hoops they make you jump through - to be overwhelming!
From the simplest deployment (maybe I don't need to make money - but want to share my ideas with the world) to the most complete deployment. I think that series would be awesome and very helpful!
You're videos are amazing, thanks for your efforts you have putted in. Can you please create a video on how to customize the notification
I can't seem to find out how to enable sound or pop up the notification card using this api for pushing a notification. It's in the Firebase cloud messaging dashboard when you send a test notification where you can enter the channel name and enable sound, but it seems this api doesn't expose all the settings. Using the code from this video if you're already in the application when you receive the push notification, you won't realize you received a notification. It only shows when you're out of the app.
Thank you for this tutorial, Topic mode is very useful 👍🏻
Yep! Depending on your use case that can come in very handy!
Thank you for this video now I can finally send push notifications to my flutter app from the admin panel. Thanks once again.
Yep shouldn’t matter wat the actual framework is you’re using!
Great great great work man ! much appreciated !!
I have a question tho about the number that should appear on the app icon. like when u get 3 notifications, there is the number 3 that appears on the icon and so on ... do you have any idea about that ?
Hi Gerald
Thank you so much for making this video 💗
I have a question:
How can I get data witch I have sent with message in xamarin forms, after I click on notification.
Sorry if my English is bad
That's it dude, thanks for explaining every detail of the notifications.
I'm happy I finally did this! :D There is still much details I can go over, but at least the bare minimum is out there now :)
Hi Donizete...
@@willian-menezes hi brother! Kkk
@jfversluis, Hello, thank you very much for making this video. There is something I want to ask you. How can I send Link(url) for notification sent with Push Notification in c#?
superb video Gerald. it helped me a lot to set up the whole environment for my app.
Great to hear!
Hi Gerald , thx a lot for the videos you are posting , you do a great job.
I did your example and works fine except
FirebasePushNotificationManager.IconResource = Resource.Drawable.appIcon;
the default notification icon wont change.
Can you please help with a suggestion ?
Thx a lot in advice
Thanks for the videos. I don't have a backend service or API, what you recommend to send Push Notifications? Embed the Send service in the Xamarin Forms Shared Project? Is it possible?Thanks
Hello, Thanks a lot, I created ConsoleApp, then I converted it to a library and I wanted to define and test the notification sending function in my xamarin project, but it is having trouble finding the private_key.json file, what should I do?
Thanks Gerald, came at the right time! Life saver!
I can read minds, watch out!
I don't know what to say ....thx u sooooo much all your videos are clear and nice and very helpful as usule ....
No problem at all! Thanks for the kind words!
Hello Mr I just wanna ask you how can I send notification when I press a button within the app it self so when user click send I got a notification in another device which is subscribed to a topic , you done this here but using a console app
do you have the link to video on change icon badge of notification?
great video summary, and great explanations ;-)
Woohoo thanks!
@Gerald Versluis - I'm using Firebase for push notifications (working fine thanks for your help)... I'd like to know how to send a push notification so that it work like a Local Notification. ie, Will show onscreen even when the power is off; Auto increments the App Icon Badge number and can be written to a local data store even when the app is closed. Do you have any videos about how to accomplish that??
I have a video on local notifications here: ua-cam.com/video/-Nj_TRPlx-8/v-deo.html
Hey Gerald, thanks for the video. I have a question.
How many topics can the console app create. In the documentation it says that an app instance can subscribe to no more than 2k topics which is great. However it doesn't mention how many topics can be created (from the console app).
I have a use case where I need to send targeted notifications to specific users. So I created a topic for each and every one based on my users' email. My user database is quite small for now, about 2k subscriptions.
Would you go with topics in this scenario, as I am, or with tokens?
Any input, thoughts are welcome.
Thanks!!
I wouldn't create a topic per user, that kind of defeats the purpose. And for a topic I can imagine you can have unlimited tokens. So think hard about how you want to create your topics and you should be good I think. If you do that right I don't see how you would even reach 2k topics :D
@@jfversluis Thank you Gerald!!
thank you so much . i want ask question what is better senario used for send notification for each user that message different from each other make a topic for each user is that right ?
It really depends on your scenario :)
Topics are more suitable to grouping people that might be interested in a certain type of notification. For example: when there is breaking news.
But if you want to build a chat app then you might want to send a notification to a specific token. Unless, you will have a group chat, then you want to have those users in that group to be in a topic and send the notification to that... Does that make sense? :D
yes thank you . so i need save a token for each user in sql server database when he open app at first time . and the admin later can send notification for each user .?
Hi Gerald thanks for the great explanation!! A quick question, how do i return the token of the device so i will store it on database so i can send to a specific user/device a message if i want?
Instead of printing it to the Console.WriteLine like I do, send it back to the server you have in place :)
@@jfversluis sorry i cant read the code from the video
@@tagathangelou Good thing you don't have to. There is a link to the repo under each video!
ive got a stupid question. do u know what the "ctl + k + d" is in visual studio for mac? im not able to figure this out :(
It depends on which scheme you have configured. I think it should list the shortcut key in the menu in the top of your screen and it should tell you in the configuration under the preferences
Thank you for this video! So, just to clarify, it looks like going through Azure Notification Hub is not necessary to send to both iOS and Android using the Firebase Admin SDK?
That is correct, Azure Notification Hub and Firebase are similar products, they allow you to send push notifications across different platforms. It makes sense to choose one or the other. This might also help: ua-cam.com/video/AKYebqOCAzY/v-deo.html
How to find the path of the json file if the we put the programs.cs code in the mainpage.cs
I don't think you should be running the from the MainPage.cs :) You would want to implement some kind of server that triggers these notifications.
If you do want to do this, add the json file to the resources and link to that docs.microsoft.com/xamarin/xamarin-forms/data-cloud/data/files?tabs=macos#loading-files-embedded-as-resources
Thank you for the tutorial.
My pleasure! It was fun to do a couple of videos on the same topic and create sort of a course :)
so its not possible to query so it reads the notifications and if it receives this specific notification it would then send you a notification with a delay of 5 seconds for 30 times?
Not sure what you mean, sorry
Thank you this saved me a lot of time
That’s the goal! Glad it was useful!
can u plz help in creating a web API (C#) to send push notifications may be after certain interval of time
I'm planning on doing push notifications again soon with .NET MAUI
Hello! Need your help, please!
I have put the private key in Shared Project root, it throws this error, "System.IO.FileNotFoundException: 'Could not find file "/private_key.json"'.
Make sure that the file is copied to the output together with the program or use any of the other methods recommended
how can i implement it in the splash screen class and not in the main activity? if I initialize it on the splash screen, the token is not generated
I'm sorry I don't understand your question, it seems to contradict each other :)
I understand the point of sending notifications thru server. But is it also okay to send notifications directly from app? So e.g. a timer ends, then send a push notification? Or is that not possible because the app has to run or be in background?
The app will have to run in the foreground for that and also; what happens if your device doesn’t have an internet connection for instance?
Finally!!! 🤩🤩🤩
A question, what do you suggest with the TOKEN? Do we have to save it on our database? And every time the users open the app, we'll have to update the token from there?
I have a cloud-based application, I'm wondering if saving the token every time the user opens the app is right so that we can retrieve the token from our server and send it through that token..I hope I'm not confusing you..😁😁
There is an event when the token refreshes. You might want to send that token back to your backend to use!
Hallo sir, thank you very much for the video. I did your example and works fine. I have a request, would you like to make tutor, to use push notification from backend.
I don’t understand. This video shows you how to do it from a backend. Take this code and put it in your ASP.NET project and it should work :)
Thanks a lot for your videos. But I have one unanswered question and the internet gave no results so far.
How do you send a pop up notification to an Android device via the API (not with the UI of FCM-Console)? It should be a minor change in the JSON because it works with the FCM-Console (like in your other video). Looking forward to a response and thank you!
Greetings. (-:
I’m not sure if I understand. If you apply what you have seen in this video in your API project it should just work
@@jfversluis I mean how to archive a popup message when using the API with a post request. For example with Postman in json format.
Thank you for this video!
Can you make a guide to send push to FCM and APNs via AWS with .Net core?
This video sends to FCM and APNS (through FCM) with .NET Core. I’m not really familiar with AWS so that will probably not happen anytime soon.
Very good! great. Thank you very much.
You’re very welcome! Glad it was helpful!
Hello. i try the step one by one but when i test send first sample notif from console firebase.. never show notif..
no error
Hey there! The debugging can be a bit hard. Check the logs on both the sending console side and the app side and try to set breakpoints to see if any of them gets hit
I am getting errors while using Token {"SenderId mismatch"}. But using Topics it is sending. What will be the reason?
Hm make sure that all api keys and such match. I’m sure you can find some more info if you search for that error message:)
Thank You... THAT helped. :)
Glad to hear it!
I've created NotificationHelper class in shared file and do as you explained
I am facing a problem in determining the private_key.json path 'Could not find file "/private_key.json"'
"I am not smart as you said 😢😢😢😢😢😢😢😢" I tried many ways
I need help!!!!
In Visual Studio Set Build Action = Content and Copy To Output Directory = Copy always. Also set proper path to the key file such as FromFileAsync("Data\\Keys\\firebaseAdminKey.json", cts.Token)
Good morning please I would like to know how to activate notifications when the user needs to send or receive the files as for example using a backup app. Please take into account my comment
Sorry I'm not sure what you mean. My videos show you how to implement the notifications, it's up to you to find the right point in your application flow when to actually trigger the notification depending on the action you would like your user to take :)
Great video, but I have a dude, how can send the notificatión to especific user or device? Thanks in advance
Save the token from the push notification and make sure you can link it to the user that it comes from, i.e. the logged in user in your app. Then you can send it to specific users!
When using FCM like this, I want to know how to elevate the IMPORTANCE of the push notification and to enable a default sound with the notification. Do you have a video that covers that?
Don't have a video about it, but you can set FirebasePushNotificationManager.DefaultNotificationChannelImportance in the Application.cs
@@jfversluis That'll be a start - I'll do it today. Thanks for all the help!
Is there a way to run the ".Send" Console app when you push a button In the main project? Or would I just add the code as a function in the main project?
From the app you mean? I wouldn't recommend sending notifications from the app directly. You'll probably always send also something to your backend service, add a trigger there to send the push notification
@@jfversluis Sorry I'm still kinda confused.... In my code I send the token to my firebase database along with a username to idenify which phone is which. When I add information about a specific user, I want that user to get a notifcation letting them know that information has been added... So instead of fetching that users token and adding it to "XFFCMPushNotificationsSample.Send" and running it, I would add a trigger through firebase and send it that way?
@@TroutsWorld It all depends on how and when you want to send it. If you want to let them know the information was added, then yes, if would make sense to trigger a piece of code from the server whenever that happens.
Although, personally I feel using a push notification for that feels a bit too much. You have to be careful with push notifications to not annoy people.
In this case why not just inspect the HTTP result code and let the user know based on that if the operation succeeded or not?
@@jfversluis Yea you're right. Thank you very much. You really help me out a lot.
Awesome! Glad to be of service :)
i got an error on initialization.when using .net web.hope you can help me to develop HTTP API
Without any details it's impossible to tell what might be wrong, sorry. You might be better off asking on Stack Overflow or a similar site :)
Thankssss sooo much🖤
You are very welcome! Glad it was helpful!
Hey general, can you help me with a small mistake that I have. I am trying to send the notification by mvvm in the general project, through a button, but I get an error. it tells me that the private_key.json was not found. Would you help me there? I would really appreciate it. Thanks in advance!!!
It’s pretty hard to help with that. Can be a lot of things. Make sure you set the right Build Action on it and double-check if the json file ends up in your app package
@@jfversluis Validate everything, the compilation is correct and the location is the same.
Hi, good video, please do you know how to push notification from sql server remotly in xamrain form s?, i don t want with api.
To be honest I think it’s a good idea to add an api between your app and sql database for several reasons. And the ability to send push notifications is one of them. I don’t think there will be a video on sending notifications directly from sql server any time soon, sorry!
Can you please make a video on scheduling the firebase push notification through code
What is your use-case here? Just trying to understand :) I think the scheduling should happen somewhere in your code, not sure if it can be done with Firebase
Gerald . You are a hero
You are really generous. Your videos helped me a lot. Big thank you.. I have a question.. If I'm to use this appraoch as an API what would be the correct verb. Put or Get
Thank you Mohammad! Appreciate it!
My suggestion would actually be to use a POST :D
@@jfversluis
Couldn't agree more ❤️
@@jfversluis I used the same code but with a tiny modification, and it worked in Xamarin.Forms like a charm, thanks to you Mr. my dream has come true, and now I'm able to send cross-platform notifications i.e from Desktop to Android and vice versa. The modification I made is: instead of getting the credentials from the .json file, I used the 'fromStream' method, and that of course, after imbedding the .json file as a resource in the shared project. Thanks a lot Mr. Gerald
That is so wonderful to read Mohammad! Thank you for taking the time to let me know! Good luck with your app!
@@jfversluis I'm actually thinking of coding a nuget package for both Xamarin.Forms and Desktop for that. and the credit will be yours for sure.
Thanks for these videos, Could you show how to do foreground FCM please..
What do you mean with foreground?
Thanks for the Video, can you close the app and receive the message when the app is closed ?
Should be possible, yes
@@jfversluis Thank you .
Thanks
is there any way to send a custom sound ?
You absolutely can. I think it does require some configuration upfront, for instance: put the custom sound in your app. Don't know from the top of my head how to do it exactly though
@@jfversluis
Do you have any documentation ?
Thumbs up for the video , another one for the T-Shirt. I looked it up everywhere online but could not find it :)? Would you share where I can buy it from ?
Thanks! You mean this one? www.bonfire.com/store/dotnet-maui/
The one you were wearing in this specific video
Aah sorry! Gotcha. That one is here: microsoftmerchandise.com/Shop/#/product/Apparel/Tops/MIC01122602-Binary-T-shirt-Charcoal-SM
Is this push notification works even the app is not running in background. Thank you for this video.
THis works even when not running in the background :)
FCM vs Azure Push Notifications? What are the tradeoffs? Thank you
Technically not much. Both solutions are kind of a layer on top of the native notifications. You will always have to go through the Apple and Google servers at the end. Of course FCM _is_ the native platform to do this for Android. So the only thing I could think of is that FCM has functionalities that are not surfaced through Azure Push Notifications. Does that makes sense? :)
@@jfversluis Makes sense. There is a nominal cost for Azure Notifications Hub at a certain threshold level. Thank you for your excellent content!
Hi, I got "The default FirebaseApp already exists." error when I call the api twice. Could you help?
Probably you're calling some initialization line twice, just remove that and do it once and you should be good
@@jfversluis Nope.
once I consume my method do this. so how to prevent it?
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(firebaseKey)
}) ;
how can you show a banner or box on notification?
Set a higher priority
Please upload video for firebase analytics in xamarin 🙏🙏🙏i m facing soo much issues
Can help i get this error :
"FirebaseMessagingException: SenderId mismatch" in c#
No clue, sorry :) but sounds like some ids are not lining up?
@@jfversluis I followed all you steps but I get onyl this error i researching on stackoverflow and medium etc. but I cant find good result anyway I keeping researching again thanks so much bro 🤗
did you find the solution ?
what about groups in firebase
is it deprecated?
Looks like it’s still a thing: firebase.google.com/docs/cloud-messaging/android/device-group
Best tutorial👍
Glad you liked it!
Quick one, on IOS notifications do come through but without a sound, is there a way around it?
There is a setting for that when sending the notification
@@jfversluis Any idea where I can find it?
What is private_key.json? Where can I get?
It’s explained in the video around the 4 minute mark
nIce, thank you.
Does this work without adding the app on firebase?
Not sure what you mean. To use Firebase you will always have to make an app registration
But how do you send it to a specific CHANNEL? What you showed here actually makes the Android to automatically create a channel called 'Miscellaneous' and not to the channel you just created.
You can specify it in the send notification body, it is a property on that object. Also see: firebase.google.com/docs/cloud-messaging/http-server-ref
Dear sir Gerald something I really appreciate will be if u make a videa about how to trigger different events or send to different pages when you tab the notification 😱🤯 blow mind 💀💜 ty , sincerely Ed.
Indeed, it would be great to a see a video about this.
I got this error:
The SSL connection could not be established, see inner exception
You probably want to have a look at the inner exception for the real reason and fix that :)
Thanks a lot
You’re welcome!
Thanks for explaining how it works!
Unfortunately I can't get a handle on the foreground notifications. How to send them when the program is open? Maybe some follow-up video?
Have you seen the iOS video? I think I mention it there
@@jfversluis ok, i'll check. Thanks!
How do I get a token based on their username?
The tokens are very random and tied to the device and your app but can change over time. There are events that are raised when a new token is issued, send that back to the server including information what their username is or however else you identify users
but sir, where can i get the registrationToken ?
That’s provided by Google. I show in the video how you get it
@@jfversluis thank you sir, your video save my life
Não funciona na API 33 Android 13.0
Onde posso encontrar documentação para isso. Desde já agradeço
The link to the plugin repository is in the video description!
@@jfversluis Continuo sem compreender, o seu conteúdo é incrível, porém deveria haver uma possibilidade de atualização no seu vídeo pois o Android 13.0 tem um comportamento bem diferente dos demais e vc é um dos únicos que fala de xamarin ainda no youtube. Se eu me tornar membro, vc grava um vídeo para nós sobre essa atualização?
Can this code send notifications for ios? thanks
Absolutely!
Hola Gerald antes que nada muchas gracias por tus videos, son geniales. Cuando quiero mandar la notificación me da error:
Excepción producida: 'System.FormatException' en System.Private.CoreLib.dll
Excepción no controlada del tipo 'System.FormatException' en System.Private.CoreLib.dll
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
Alguna idea de lo que pude ser? muchas gracias.
WOW!! PERFECT. WOULD IT WORK IN MVVM?
Sure! Not all things here can be handled here with MVVM as you’re dealing with platform stuff but you using MVVM in this case shouldn’t matter
@@jfversluis
I've been trying but it gives me an error when looking for the private_key.json, I don't know if I have to specify the path in another way
Can you please make a tutorial on how to convert existing balzor web assembly project to asp.net core hosted app if we have separate api project.
Sorry, I'm not sure what you mean with this :) You already have a Blazor WebAssembly project? And you want to convert that?
@@jfversluis yes have a separate blazor wasm project and a separate asp.net core Api project.
and when we create new wasm project using visual studio there is a check box called asp.net core hosted by check this checkbox vs create three projects for us one is client other is server and the third one is shared.in my case when i start developing my blazor project i have no idea about aso.net core hosted so i create separate project for wasm and separate api project as i mentioned above.but now when i want to deploye my app on server i need two different websites for hosting two projects one for api and other for client app.by using asp.net core hosted i just have to use one website.so please guid me to turn my app at this stage to asp.net core hosted
Thanks.
Thank bro
According to your post I can implement my first app with notification :D
Woohoo! My pleasure!
Is this must push message to multiple xamarin apps?
Sorry, I’m not sure if I understand
@@jfversluis i created app with xamarin , and implement push notification with FCM by your lesson for android , now i installed it to 3 android phones, but only 1 receive push notification
@@jfversluis And so i asked question: "Is this method must send notification for all phones with my app?"
@@jfversluis sorry it doesn't work only with android 12...
If you want to send 1 notification to all your users at once you probably want to let them subscribe to a topic instead of looping through all tokens
Hello. Please show how you can send a push to an ios device in the same way. Thank you.
This should also send notifications to iOS devices!
@@jfversluis Thanks a lot!
I have a question because I did not find the information.
Is there a life cycle of tokens or is it unlimited?
The problem is that it is sent to iphone 13, but not to an earlier version. Can you give me a hint where to dig?
why not an async Task Main, Gerald?!!!) Looks like a .Result propaganda :D
I knowwwww! I already said it was dirty?! ;(
But it's not possible yet with this version of .NET!
Please go step by step.
I don’t understand, I think that’s what I’m doing 😄
Guys, this method won't work on Android 12 , for fix this add
in tag in AndriodManifest.xml
Thanks for letting us know!
@@jfversluis 😅