swiftfirebasegoogle-cloud-functions

Send firebase push notification programmatically


I have a iOS messaging app (Swift) where a chat consists of x users. A single user can be part of many chats and the groupChats collections contains all the group chats between users for an app. The allUsersUID is an array that contains the firebase UIDs of all users in that chat. The texts collection contains all the messages for the specific chat. Users create a new document in that collection when they send a message, and listen to the same collection for new messages from other users.

If user X sends a new message to the texts collection, how can a push (banner, push, alert) notification be sent to users A, B, C, can user X programmatically send this notification to all other users? I read this SO thread but the answer was from 2018 and seems outdated.

enter image description here


Solution

  • Firebase Cloud Messaging has no knowledge of your users, so you will have to make that connection yourself in the application.

    The most common approach for this is to get the FCM token for each user on each device, and store those tokens-per-users in a database (sometimes referred to as the token registry). Then when you want to notify a user, you read their device tokens from the registry, and call the API to send a message to those tokens. This sending of a message has to happen on a trusted environment, such as a server that you control, or something like Cloud Run/Cloud Functions.

    In addition to the links I provided above, I also recommend reading the Firebase documentation's best practices for FCM registration token management.