Table of Contents
- 1. Introduction
- 2. Prerequisites
- 3. Basic Concepts
- 4. Setup and Configuration
- 5. Implementation
- 6. Testing and Troubleshooting
- 7. Best Practices
- 8. Conclusion
Introduction
Push notifications have become an essential feature in modern mobile applications, enabling real-time user engagement and improved app retention. This comprehensive guide will walk you through implementing push notifications in your React Native application, covering both iOS and Android platforms.
What You’ll Learn
- Setting up Firebase Cloud Messaging (FCM) and Apple Push Notification Service (APNS)
- Implementing push notifications in React Native
- Handling notifications in foreground and background states
- Testing and troubleshooting push notifications
Prerequisites
Before starting, ensure you have:
- Node.js installed (version 12 or higher)
- React Native development environment set up
- Xcode (for iOS development)
- Android Studio (for Android development)
- A Firebase account
- An Apple Developer account (for iOS)
Basic Concepts
Push Notification Architecture
- 1. Provider (Your Server)
- 2. Platform Notification Service (FCM/APNS)
- 3. Device
- 4. Application
Types of Notifications
- Foreground notifications
- Background notifications
- Silent notifications
Setup and Configuration
Firebase Setup
- 1. Create a new Firebase project
- 2. Add your iOS and Android apps
- 3. Download configuration files:
- google-services.json (Android)
- GoogleService-Info.plist (iOS)
iOS Configuration
1. Configure certificates:
# Generate push notification certificate
fastlane pem -a com.your.bundleid
2. Add capabilities in Xcode:
- Push Notifications
- Background Modes
Android Configuration
1. Add FCM configuration to android/app/build.gradle:
dependencies {
implementation 'com.google.firebase:firebase-messaging:23.0.0'
}
2. Update Android Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
Implementation
1. Install Required Dependencies
npm install @react-native-firebase/app @react-native-firebase/messaging
npm install @react-native-community/push-notification-ios # for iOS
2. Initialize Firebase Messaging
// App.js
import messaging from '@react-native-firebase/messaging';
async function requestUserPermission() {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('Authorization status:', authStatus);
}
}
3. Handle Foreground Messages
useEffect(() => {
const unsubscribe = messaging().onMessage(async remoteMessage => {
console.log('Received foreground message:', remoteMessage);
// Handle notification display
});
return unsubscribe;
}, []);
4. Handle Background Messages
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Message handled in the background:', remoteMessage);
});
5. Custom Notification Handler
const NotificationHandler = {
displayNotification: async (title, body) => {
// For Android
if (Platform.OS === 'android') {
await notifee.displayNotification({
title,
body,
android: {
channelId: 'default',
smallIcon: 'ic_launcher',
},
});
}
// For iOS
else {
PushNotificationIOS.addNotificationRequest({
id: String(Date.now()),
title,
body,
});
}
},
};
Testing and Troubleshooting
Testing Methods
1. Firebase Console Testing
2. Command Line Testing:
# For Android
firebase messaging:send --token=<device_token> \
--message="{\"notification\":{\"title\":\"Test\",\"body\":\"Message\"}}"
Common Issues and Solutions
1. Notification Not Receiving
- Check Firebase configuration
- Verify permissions
- Ensure token registration
2. iOS Specific Issues
- Certificate validation
- Provisioning profile setup
- Background modes configuration
3. Android Specific Issues
- Channel ID configuration
- Firebase service file placement
- Manifest permissions
Best Practices
1. Token Management
const storeToken = async (token) => {
try {
await AsyncStorage.setItem('fcmToken', token);
} catch (error) {
console.log('Error storing token:', error);
}
};
2. Battery Optimization
// Implement proper unsubscribe methods
useEffect(() => {
const unsubscribe = setupNotifications();
return () => unsubscribe();
}, []);
3. Error Handling
const handleNotificationError = (error) => {
console.error('Notification Error:', error);
// Implement proper error reporting
};
Security Checklist
- Validate notification payload
- Implement proper token refresh
- Secure server-side implementation
- Handle expired tokens
Conclusion
Key Takeaways
- 1. Proper setup is crucial for both platforms
- 2. Handle both foreground and background scenarios
- 3. Implement proper error handling
- 4. Follow platform-specific guidelines