向 iOS 发送推送通知的问题,(云功能)

Posted

技术标签:

【中文标题】向 iOS 发送推送通知的问题,(云功能)【英文标题】:Problem to send send push notifications to iOS, (cloud function) 【发布时间】:2021-12-04 14:10:14 【问题描述】:

我目前非常卡在 ios 的推送通知中,(适用于 android,但不适用于 iOS)

我已正确设置所有内容,并且知道如何通过云消息传递控制台发送推送通知。

我为此使用 google firebase 函数:

有谁知道如何在 iOS 上解决这个问题,我很困惑,它适用于 android。

const functions = require("firebase-functions");
const  firestore, messaging  = require("./admin");
const PromiseAllSettled = require("promise.allsettled");

/**
 *
 * Sends only to doctor when appointment doc is
 * created.
 *
 * Push notification to every device token
 * the doctor has.
 *
 */
const pushOnCreate = functions.firestore
  .document("appointments/id")
  .onCreate(async (snap) => 
    const data = snap.data();
    const doctorId = data.doctorId;

    var tokenDocument = await firestore
      .collection("doctors")
      .doc(doctorId)
      .collection("tokens")
      .orderBy("createdAt", "desc")
      .get()
      .then((snapshot) => 
        if (!snapshot.empty) 
          let pushTokenList = [];
          snapshot.forEach((doc) => 
            pushTokenList.push(doc.data().pushToken);
          );
          return  success: true, payload: pushTokenList ;
         else 
          return  noData: true ;
        
      )
      .catch((error) => 
        console.log("Error while getting token documents", error);
        return  error: error.toString() ;
      );

    if (tokenDocument.success !== undefined) 
      // Create a list of promises
      let tokenList = tokenDocument.payload;
      let promiseList = [];

      tokenList.forEach((token) => 
        console.log(`Create notification token for: `, token);
        const payload = 
          token: token,
          notification: 
            title: "Nouveau rendez-vous",
            body: "Vous avez un nouveau rendez-vous pour " + data.title,
          ,
          android: 
            priority: "high",
            notification: 
              title: "Nouveau rendez-vous",
              body: "Vous avez un nouveau rendez-vous pour " + data.title,
              priority: "max",
              clickAction: "FLUTTER_NOTIFICATION_CLICK",
              channelId: "appointment_channel",
              defaultSound: true,
              defaultVibrateTimings: true,
              defaultLightSettings: true,
              visibility: "public",
              ticker: "Nouveau rendez-vous",
            ,
          ,
          apns: 
            headers: 
              "apns-priority": "10",
            ,
            payload: 
              aps: 
                alert: 
                  title: "Nouveau rendez-vous",
                  body: "Vous avez un nouveau rendez-vous pour " + data.title,
                ,
                sound: 
                  critical: true,
                  name: "default",
                  volume: 1.0,
                ,
              ,
            ,
          ,
        ;

        // Add new promise to the list of promises.
        const newPromise = messaging.send(payload);
        promiseList.push(newPromise);
      );

      return await PromiseAllSettled(promiseList)
        .then((_) => 
          console.log(`Notification Sent`);
          return true;
        )
        .catch((e) => 
          console.error(`Notification operation failed.`,  details: e );
          return false;
        );
     else 
      console.log("Either no data or an error");
      return Promise.resolve("Either no data or an error");
    
  );

/**
 *
 * Sends notification to user when the doctor is online
 * and ready for the appointment.
 *
 */
const pushOnUpdate = functions.firestore
  .document("appointments/id")
  .onUpdate(async (change) => 
    const beforeData = change.before.data();
    const data = change.after.data();
    const userId = data.userId;
    const isDoctorActive = data.isDoctorActive;
    const isUserActive = data.isUserActive;

    if (isUserActive) 
      console.log("User is already active");
      return Promise.resolve();
    

    // If the doctor is active and user is not active only then send the notification to the user.
    if (isDoctorActive && !beforeData.isUserActive) 
      var tokenDocument = await firestore
        .collection("users")
        .doc(userId)
        .collection("tokens")
        .orderBy("createdAt", "desc")
        .get()
        .then((snapshot) => 
          if (snapshot.empty) 
            console.log("No matching documents.");
            return  noData: true ;
           else 
            let pushTokenList = [];
            snapshot.forEach((doc) => 
              pushTokenList.push(doc.data().pushToken);
            );
            return  success: true, payload: pushTokenList ;
          
        )
        .catch((error) => 
          console.log("Error while getting token documents", error);
          return  error: "Error" ;
        );

      // After getting the document send the notification message.
      if (tokenDocument.success !== undefined) 
        // Create a list of promises
        let tokenList = tokenDocument.payload;
        let promiseList = [];

        // Loop through it and create a promise list
        tokenList.forEach((token) => 
          console.info("Create notification for token ", token);
          // Create the notification object.
          const payload = 
            token: token,
            notification: 
              title: "Votre psychologue est en ligne",
              body:
                "Ç'est l'heure de votre séance de " +
                data.title +
                ". Accédez y vite.",
            ,
            data: 
              appointmentDocument: JSON.stringify(data),
            ,
            android: 
              priority: "high",
              notification: 
                title: "Votre psychologue est en ligne",
                body:
                  "Ç'est l'heure de votre séance de " +
                  data.title +
                  ". Accédez y vite.",
                priority: "max",
                clickAction: "FLUTTER_NOTIFICATION_CLICK",
                channelId: "appointment_channel",
                defaultSound: true,
                defaultVibrateTimings: true,
                defaultLightSettings: true,
                visibility: "public",
                ticker: "Nouveau rendez-vous",
              ,
            ,
            apns: 
              headers: 
                "apns-priority": "10",
              ,
              payload: 
                aps: 
                  alert: 
                    title: "Votre psychologue est en ligne",
                    body:
                      "Ç'est l'heure de votre séance de " +
                      data.title +
                      ". Accédez y vite.",
                  ,
                  sound: 
                    critical: true,
                    name: "default",
                    volume: 1.0,
                  ,
                ,
              ,
            ,
          ;
          // Add new promise to the list of promises.
          const newPromise = messaging.send(payload);
          promiseList.push(newPromise);
        );

        return await PromiseAllSettled(promiseList)
          .then((_) => 
            console.log(`Notification Sent`);
            return true;
          )
          .catch((e) => 
            console.error(`Notification operation failed.`,  details: e );
            return false;
          );
       else 
        console.log("No token document found as there was an error");
        return Promise.resolve("No token document found as there was an error");
      
     else 
      console.log(
        "Doctor is not active or the user was just active and is not active now."
      );
      return Promise.resolve();
    
  );

module.exports = 
  pushOnCreate,
  pushOnUpdate,
;

【问题讨论】:

你用的是真机还是模拟器? 真实设备(iPhone 8) 【参考方案1】:

您可能需要向 APNS 注册您的应用程序,才能接收通知: https://developer.apple.com/documentation/usernotifications/registering_your_app_with_apns

【讨论】:

我已经这样做了,兄弟。感谢您的帮助 ApnsError的错误码是什么? 你能帮我修改一下代码吗(如果可以的话) 我没有任何 apns 错误 "it's not working" 不是错误描述...而且我看不到修复代码的动力,尤其是当您自己懒得查找返回的错误代码时,这会使这是一个正确的问题……有效载荷很可能是错误的;例如。 iOS 上的声音文件通常以 *.aiff 结尾。

以上是关于向 iOS 发送推送通知的问题,(云功能)的主要内容,如果未能解决你的问题,请参考以下文章

如何在 iOS 中使用 Google Firebase 向特定用户发送推送通知?

苹果推送通知问题

如何通过 GCM 向 iOS 设备发送推送通知?

解析从云代码向特定用户发送推送通知

向 iOS PushSharp 证书发送推送通知

通过 FCM 发送推送通知时何时使用 iOS 设备令牌?