When building a real-time video streaming application, integrating push notifications is essential to enhance user engagement and provide timely updates. In this blog post, I’ll share the steps I took to connect Firebase push notifications with Ant Media’s Flutter SDK. However, note that this is not a tutorial on setting up an Ant Media Server. For an easy guide to setting up Ant Media Server on AWS, you can refer to this video tutorial.
Prerequisites
Before diving into the integration, ensure you have the following:
- Flutter Installed: If you haven’t installed Flutter yet, follow the official installation guide.
- Ant Media’s Flutter SDK Sample: I will be using our example project. You can find the SDK and sample applications on the official GitHub repository. Clone the repository and run the sample project to get started.
Overview of the Integration Process
In this post, I will guide you through:
- Connecting Firebase Cloud Messaging (FCM) to your Flutter project.
- Setting up a Flask backend to handle Ant Media Server webhooks.
- Using the Flask backend to forward notifications to your Flutter app.
Setting Up Firebase Cloud Messaging (FCM)
To enable push notifications in your Flutter app, you’ll need to integrate Firebase with your project. Follow the steps in the FlutterFire documentation to connect Firebase to your Flutter project and configure Firebase Cloud Messaging (FCM).
Adding the Firebase API in Your Flutter Project
After configuring Firebase, we can use the firebase_api.dart file from our SDK in our entry point like in this example:
import 'package:ant_media_flutter/firebase_api.dart';
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await FirebaseApi().initNotifications();
return runApp(
const MaterialApp(
home: MyApp(),
debugShowCheckedModeBanner: false,
)
);
}
With the firebase_api.dart class added to your project, you can now test the connection. Run your Flutter app, and if everything is set up correctly, you should see a print statement in the console with the token: Token: <fCMToken>
. Copy this token as it will be used to send a test message later.
Sending a Test Message from Firebase Console
To send a test notification, follow these steps:
- Go to the Firebase Console.
- On the left-hand side open the Run drop-down button, and select Messaging.
- Click on New Campaign and choose the Notification option.
- Add a test title and body for your notification.
- Click on Send Test Message.
- In the dialog box, paste the FCM token you copied earlier.
- Send the notification and verify that it appears in your app.
If the notification is successfully received, congratulations! Your app is now set up to handle push notifications.
Setting Up the Flask Backend and Ngrok
For handling webhooks and sending notifications to your Flutter app, I wrote a Flask application and hosted it on my Ubuntu virtual machine. To make the server accessible over the internet, I used Ngrok. Here’s how you can set it up:
- Install Flask and Required Dependencies: Follow the Flask installation guide to set up Flask on your system. Additionally, install the necessary Python dependencies using the command:
pip install flask firebase-admin
- Install Ngrok: Download and set up Ngrok by following the Ngrok quickstart guide. Note that Ngrok is only required if you are using a local network. If you have a public IP, you can use that as the Ant Media webhook URL instead.
Flask Application Code, be sure to replace the certificate path and FCM token fields:
from flask import Flask, request, jsonify
import firebase_admin
from firebase_admin import credentials, messaging
# Initialize Flask app
app = Flask(__name__)
# Initialize Firebase Admin SDK
cred = credentials.Certificate("someflutter-firebase.json") # Replace with the path to your Firebase Admin JSON file
firebase_admin.initialize_app(cred)
# Function to send notification to a device
def send_notification_to_device(token, title, body, data=None):
try:
# Create a message with optional data payload
message = messaging.Message(
notification=messaging.Notification(title=title, body=body),
token=token,
data=data if data else {}
)
# Send the message via FCM
response = messaging.send(message)
print(f"Notification sent successfully: {response}")
except Exception as e:
print(f"Error sending notification: {e}")
# Flask route to handle incoming webhook POST requests
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
data = request.json
print(f"Received POST data: {data}")
# Extract necessary information from the webhook payload
if data:
# Example of extracting fields (adjust based on your webhook structure)
device_token = "" # Replace with actual field for the device's FCM token we copied earlier
action = data.get('action')
id = data.get('id')
title = "Action: " + action
body = "StreamId: " + id
additional_data = data.get('data', {}) # Optional additional data
if device_token:
# Send notification to the device
send_notification_to_device(device_token, title, body, additional_data)
else:
print("Device token not provided in the payload.")
return jsonify({"message": "POST request received and processed"}), 200
return "This is the GET response"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000)
Running the Flask App and Ngrok
Run the Flask application using the following command:flask --app main run
Next, start Ngrok to expose your local Flask server:
ngrok http http://localhost:5000
This will generate a public URL that can be used to send webhooks to your Flask server.
Adding Ngrok URL to Ant Media Server Webhook Settings
To finalize the integration, update the webhook URL in the Ant Media Server settings:
- Open the Ant Media Server management console.
- Navigate to Settings > Webhooks.
- Paste the public URL generated by Ngrok (e.g.,
https://<your-ngrok-id>.ngrok.io
) into the webhook URL field. - Save the changes.
With the webhook URL set, Ant Media Server will send notifications to your Flask application whenever an event occurs. Read up on the webhook event’s here. Your app is now fully integrated and ready to handle real-time updates! In case you run into issues you can always contact us through support@antmedia.io