Vedi anche https://rnfirebase.io/
Se hai iniziato il progetto con Expo Managed, esegui:
npx expo prebuild
Questo ti trasformerĂ il progetto in Bare Workflow, permettendoti di usare librerie native.
npm install @react-native-firebase/app @react-native-firebase/messaging
Android
Vai su Firebase Console, crea il progetto e aggiungi la tua app Android.
Scarica google-services.json e inseriscilo in android/app/.
Modifica android/build.gradle e android/app/build.gradle seguendo la documentazione di react-native-firebase.
iOS
Aggiungi la tua app iOS su Firebase, scarica GoogleService-Info.plist e inseriscilo in ios/.
Installa i pod:
bash
cd ios
pod install
SullâApp.js
useEffect(() => {
messaging().requestPermission();
messaging()
.getToken()
.then((token) => {
console.log("FCM token:", token);
});
messaging().subscribeToTopic("all");
const unsubscribe = messaging().onMessage(async (remoteMessage) => {
console.log("A new FCM message arrived!", remoteMessage);
Alert.alert(
remoteMessage.notification?.title
? remoteMessage.notification?.title
: "Notifiche",
remoteMessage.notification?.body
);
});
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
console.log("Message handled in the background!", remoteMessage);
});
messaging().onNotificationOpenedApp((remoteMessage) => {
console.log(
"Notification caused app to open from background state:",
remoteMessage.notification
);
});
messaging().onNotificationOpenedApp((remoteMessage) => {
// Qui gestisci l'ID della notifica
console.log("Notifica aperta:", remoteMessage);
// Naviga, mostra dettagli, ecc.
});
// Se l'app è STATA aperta tramite notifica (da stato terminated)
messaging()
.getInitialNotification()
.then((remoteMessage) => {
console.log("App avviata tramite notifica:", remoteMessage);
// Naviga, mostra dettagli, ecc.
});
return unsubscribe;
}, []);
{
"expo":
{
"notification": {
"icon": "./assets/icon.png",
"color": "#ffffff",
"iosDisplayInForeground": true,
"androidMode": "default"
},
"ios":{
[...]
"entitlements": {
"aps-environment": "production"
},
"infoPlist": {
"UIBackgroundModes": ["remote-notification"]
},
"googleServicesFile": "./GoogleService-Info.plist"
},
"android":{
"googleServicesFile": "./google-services.json",
[...]
}
"plugins": [
[...]
"@react-native-firebase/app",
"@react-native-firebase/messaging",
]
}
}
Download the google-services.json file and place it inside of your project at the following location: /android/app/google-services.json.
Configure Firebase with Android credentials
To allow Firebase on Android to use the credentials, the google-services plugin must be enabled on the project. This requires modification to two files in the Android directory.
First, add the google-services plugin as a dependency inside of your /android/build.gradle file:
buildscript {
dependencies {
// ... other dependencies
classpath 'com.google.gms:google-services:4.4.3'
// Add me --- /\
}
}
Lastly, execute the plugin by adding the following to your /android/app/build.gradle file:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services' // <- Add this line
On the Firebase console, add a new iOS application and enter your projects details. The âiOS bundle IDâ must match your local project bundle ID. The bundle ID can be found within the âGeneralâ tab when opening the project with Xcode.
Download the GoogleService-Info.plist file.
Using Xcode, open the projects /ios/{projectName}.xcworkspace
Right click on the project name and âAdd filesâ to the project, as demonstrated below:
Select the downloaded GoogleService-Info.plist file from your computer, and ensure the âCopy items if neededâ checkbox is enabled.
To allow Firebase on iOS to use the credentials, the Firebase iOS SDK must be configured during the bootstrap phase of your application.
To do this, open your /ios/{projectName}/AppDelegate.swift file and add the following:
At the top of the file, import the Firebase SDK right after 'import ReactAppDependencyProvider':
import Firebase
Within your existing application method, add the following to the top of the method:
override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// Add me --- \/
FirebaseApp.configure()
// Add me --- /\
// ...
}
Error:
The Swift pod `FirebaseCoreInternal` depends upon `GoogleUtilities`, which does not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set `use_modular_headers!` globally in your Podfile, or specify `:modular_headers => true` for particular dependencies.
We need also to update ios\ĂPodfile
[...]
target 'PdBConferimenti' do
use_expo_modules!
pod 'Firebase', :modular_headers => true
pod 'FirebaseCoreInternal', :modular_headers => true
pod 'GoogleUtilities', :modular_headers => true
pod 'FirebaseCore', :modular_headers => true
[...]
per testare lâinvio di notifiche è possibile usare questo script pyhton.
Installa le dipendenze:
pip install firebase_admin
sendNotif.py:
import firebase_admin
from firebase_admin import credentials, messaging
cred = credentials.Certificate("conferimenti-nebbiolo.json")
firebase_admin.initialize_app(cred)
def send_fcm_to_topic(topic: str, title: str, body: str, data: dict = None):
"""Invia una notifica FCM a tutti gli iscritti a un topic."""
message = messaging.Message(
notification=messaging.Notification(
title=title,
body=body
),
topic=topic,
data=data if data else {}
)
try:
response = messaging.send(message)
print(f'Notifica inviata con successo: {response}')
except Exception as e:
print(f'Errore nell\'invio della notifica: {e}')
# Esempio di utilizzo:
if __name__ == "__main__":
send_fcm_to_topic(
topic="all",
title="Titolo Notifica",
body="Testo della notifica",
data={"ticketId": "3"}
)
per eseguire:
py sendNotif.py