FCM (Firebase Cloud Messaging) 是Google提供的跨平台消息推送服务,允许开发者向iOS和Android设备发送通知和消息。在React Native应用中实现自定义FCM推送通知需要理解以下核心概念:
yarn add @react-native-firebase/app @react-native-firebase/messaging
cd ios && pod install
ios/YourAppName.xcworkspace
#import <Firebase.h>
#import <UserNotifications/UserNotifications.h>
#import <RNCPushNotificationIOS.h>
// 在didFinishLaunchingWithOptions中添加
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[FIRApp configure];
// 请求通知权限
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
dispatch_async(dispatch_get_main_queue(), ^{
[application registerForRemoteNotifications];
});
}
}];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
// 处理注册APNs token
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[FIRMessaging messaging].APNSToken = deviceToken;
[RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
import messaging from '@react-native-firebase/messaging';
import {Platform} from 'react-native';
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);
getFcmToken();
}
}
async function getFcmToken() {
try {
const token = await messaging().getToken();
console.log('FCM Token:', token);
// 将token发送到你的服务器
} catch (error) {
console.log('Failed to get FCM token', error);
}
}
// 监听前台通知
messaging().onMessage(async remoteMessage => {
console.log('Foreground notification:', remoteMessage);
// 使用react-native-push-notification等库显示本地通知
PushNotification.localNotification({
title: remoteMessage.notification.title,
message: remoteMessage.notification.body,
// 其他自定义参数...
});
});
// 设置后台消息处理器
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Background notification:', remoteMessage);
// 处理后台通知逻辑
return Promise.resolve();
});
// 监听通知点击
messaging().onNotificationOpenedApp(remoteMessage => {
console.log('Notification opened app:', remoteMessage);
// 处理点击逻辑
});
// 检查应用是否通过通知启动
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
console.log('App opened from notification:', remoteMessage);
// 处理启动逻辑
}
});
要在iOS上显示自定义通知,需要在服务器端发送包含特定payload的通知:
{
"to": "DEVICE_FCM_TOKEN",
"content_available": true,
"priority": "high",
"notification": {
"title": "自定义标题",
"body": "自定义内容",
"sound": "default"
},
"data": {
"customKey": "customValue",
"click_action": "FLUTTER_NOTIFICATION_CLICK"
}
}
要实现完全自定义的通知UI,需要:
didReceive(_:withContentHandler:)
方法import UserNotifications
class NotificationService: UNNotificationServiceExtension {
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
guard let bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) else {
return
}
// 修改通知内容
bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"
bestAttemptContent.body = "\(bestAttemptContent.body) [modified]"
// 添加自定义附件
if let url = URL(string: "https://example.com/image.jpg"),
let data = try? Data(contentsOf: url),
let attachment = try? UNNotificationAttachment(identifier: "image", url: url, options: nil) {
bestAttemptContent.attachments = [attachment]
}
contentHandler(bestAttemptContent)
}
}
registerForRemoteNotifications
content_available: true
标志onNotificationOpenedApp
或getInitialNotification
通过以上步骤,你可以在React Native iOS应用中实现完整的自定义FCM推送通知功能,包括自定义UI和交互逻辑。
没有搜到相关的文章