使用Firebase Cloud Messaging进行跨平台推送通知

算法之美 2020-10-15 ⋅ 18 阅读

Firebase Cloud Messaging(以下简称FCM)是一个由Google提供的跨平台消息传递解决方案。它可以帮助开发人员在Web、Android和iOS等平台上向用户发送推送通知。FCM不仅提供了简单的文本消息推送功能,还可以发送富文本、图片和链接等内容,以更好地吸引用户的注意力。

集成FCM到你的应用

首先,你需要在Firebase控制台创建一个项目,并设置好Android和iOS应用的详细信息。详细的步骤可以在Firebase文档中找到。

安装FCM SDK

对于Android应用,使用如下代码在build.gradle文件中添加FCM SDK依赖:

implementation 'com.google.firebase:firebase-messaging:20.1.7'

对于iOS应用,在Podfile文件中添加FCM库:

pod 'Firebase/Messaging'

注册设备端到FCM

Android应用需要创建一个继承自FirebaseMessagingService的类,并且在onTokenRefresh方法中获取设备的FCM令牌(token):

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onTokenRefresh() {
        String token = FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken();
        //将token发送到自己的服务器
    }
}

iOS应用需要在AppDelegate中,向FCM注册设备的令牌(token):

import Firebase
import FirebaseInstanceID

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    FirebaseApp.configure()
    
    // 获取FCM token
    InstanceID.instanceID().instanceID { (result, error) in
        if let error = error {
            print("Error fetching remote instange ID: \(error)")
        } else if let result = result {
            print("Remote instance ID token: \(result.token)")
            //将token发送到自己的服务器
        }
    }
    
    return true
}

向单台设备发送推送通知

要向单台设备发送推送通知,可以使用Firebase的API:

curl -X POST -H "Authorization: key=<your_server_key>" -H "Content-Type: application/json" -d '{
  "to" : "<device_token>",
  "data" : {
      "title" : "Hello",
      "body" : "World"
   }
}' "https://fcm.googleapis.com/fcm/send"

其中,<your_server_key>是你的FCM项目的服务器密钥,<device_token>是你要发送通知的设备的令牌。

向群体设备发送推送通知

要向群体设备发送推送通知,可以使用Firebase的API,指定一个设备组的名称:

curl -X POST -H "Authorization: key=<your_server_key>" -H "Content-Type: application/json" -d '{
  "to": "/topics/<topic_name>",
  "data": {
      "title" : "Hello",
      "body" : "World"
   }
}' "https://fcm.googleapis.com/fcm/send"

其中,<your_server_key>是你的FCM项目的服务器密钥,<topic_name>是你要发送通知的设备组的名称。

接收推送通知

在Android应用中,创建一个继承自FirebaseMessagingService的类,并在onMessageReceived方法中处理接收到的推送通知:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // 处理推送通知
        if (remoteMessage.getData().size() > 0) {
            // 获取通知的标题和内容
            String title = remoteMessage.getData().get("title");
            String body = remoteMessage.getData().get("body");
            
            // 显示通知
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
                    .setSmallIcon(R.drawable.ic_notification)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT);

            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
            notificationManager.notify(0, builder.build());
        }
    }
}

在iOS应用中,在AppDelegate类中添加如下代码来处理接收到的推送通知:

import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // 这里做一些其他的初始化操作
        
        // 配置FCM
        FirebaseApp.configure()
        Messaging.messaging().delegate = self
        UNUserNotificationCenter.current().delegate = self
        
        // 请求权限
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {_, _ in })
        
        // 获取FCM token
        Messaging.messaging().token { token, error in
            if let error = error {
                print("Error fetching FCM token: \(error)")
            } else if let token = token {
                print("FCM token: \(token)")
            }
        }
        
        application.registerForRemoteNotifications()
        
        return true
    }
    
    // 处理接收到的推送通知
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {        
        if let title = userInfo["title"] as? String,
            let body = userInfo["body"] as? String {
            // 显示通知
            let content = UNMutableNotificationContent()
            content.title = title
            content.body = body
            
            let request = UNNotificationRequest(identifier: "notification", content: content, trigger: nil)
            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
        }
    }
    
    // iOS 10以上的处理方法
    @available(iOS 10, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .badge, .sound])
    }
    
    @available(iOS 10, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // 这里可以根据用户的操作进行相应的处理
        completionHandler()
    }
    
    // iOS 10以下的处理方法
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        if let title = userInfo["title"] as? String,
            let body = userInfo["body"] as? String {
            // 显示通知
            let content = UNMutableNotificationContent()
            content.title = title
            content.body = body
            
            let request = UNNotificationRequest(identifier: "notification", content: content, trigger: nil)
            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
        }
        
        completionHandler(.newData)
    }
    
    // 注册设备令牌
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        //将token发送到自己的服务器
    }
}

结语

使用Firebase Cloud Messaging可以轻松地向Web、Android和iOS等平台的用户发送推送通知。我们可以通过集成FCM SDK、注册设备端、发送推送通知和处理接收到的推送通知等步骤,完成一个完整的推送通知功能。希望本文对你有所帮助,感谢阅读!


全部评论: 0

    我有话说: