name: push-notification-setup description: 使用Firebase Cloud Messaging和本地服务在iOS、Android和Web上实现推送通知。用于添加通知功能、处理后台消息或设置通知通道时。 keywords: 推送通知, FCM, Firebase Cloud Messaging, iOS通知, Android通知, Web通知, React Native通知, 通知权限, 后台消息, 通知通道, APNS, APNs, 通知令牌, 远程通知, 前台通知, 通知处理程序
推送通知设置
在移动和Web平台上实现推送通知。
Firebase Cloud Messaging (React Native)
import messaging from '@react-native-firebase/messaging';
// 请求权限
async function requestPermission() {
const status = await messaging().requestPermission();
if (status === messaging.AuthorizationStatus.AUTHORIZED) {
const token = await messaging().getToken();
await sendTokenToServer(token);
}
}
// 处理前台消息
messaging().onMessage(async message => {
console.log('前台消息:', message);
showLocalNotification(message);
});
// 处理后台/退出消息
messaging().setBackgroundMessageHandler(async message => {
console.log('后台消息:', message);
});
// 处理令牌刷新
messaging().onTokenRefresh(token => {
sendTokenToServer(token);
});
iOS Native (Swift)
import UserNotifications
func requestAuthorization() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
sendTokenToServer(token)
}
Android (Kotlin)
class MyFirebaseService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
sendTokenToServer(token)
}
override fun onMessageReceived(message: RemoteMessage) {
message.notification?.let {
showNotification(it.title, it.body)
}
}
private fun showNotification(title: String?, body: String?) {
val channelId = "default"
val notification = NotificationCompat.Builder(this, channelId)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_notification)
.build()
NotificationManagerCompat.from(this).notify(0, notification)
}
}
最佳实践
- 在适当的时间请求权限
- 处理令牌刷新
- 支持通知通道(Android)
- 实现深度链接
- 不要在有效载荷中发送敏感数据
- 在真实设备上测试