美文网首页
expo react-native 消息推送

expo react-native 消息推送

作者: 朱传武 | 来源:发表于2021-06-07 11:07 被阅读0次

今天有个巴基斯坦友人求助expo消息推送,之前国内一直用极光之类,所以类似expo推送之前还真没接触过,对方把项目源码发过来之后,我对照了官方文档看了下流程,帮其解决了问题,不过,expo推送使用起来是真的很方便,现在记录如下:

官方文档(https://docs.expo.io/versions/latest/sdk/notifications/#sending-notifications-directly-through-apns-and-fcm

因为客户发过来源码的时候,已经集成了相关的库以及配置好了原生部分,所以此处我就只是大体一看,具体流程:https://github.com/expo/expo/tree/master/packages/expo-notifications

expo install expo-notifications

安卓我没试,所以这里就先不写了。

代码使用

获取token
 registerForPushNotificationsAsync().then((token: any) => {
      global.token = token;
      console.log("====================================");
      console.log(token);
      console.log("====================================");
    });

registerForPushNotificationsAsync具体实现为:

export async function registerForPushNotificationsAsync() {
    let token;
    if (Constants.isDevice) {
        const {
            status: existingStatus,
        } = await Notifications.getPermissionsAsync();
        let finalStatus = existingStatus;
        if (existingStatus !== 'granted') {
            const { status } = await Notifications.requestPermissionsAsync();
            finalStatus = status;
        }
        if (finalStatus !== 'granted') {
            alert('Failed to get push token for push notification!');
            return;
        }
        token = (await Notifications.getExpoPushTokenAsync()).data;
    } else {
        alert('Must use physical device for Push Notifications');
    }

    if (Platform.OS === 'android') {
        Notifications.setNotificationChannelAsync('default', {
            name: 'default',
            importance: Notifications.AndroidImportance.MAX,
            vibrationPattern: [0, 250, 250, 250],
            lightColor: '#FF231F7C',
        });
    }

    return token;
}
注册监听事件
useEffect(() => {
    registerForPushNotificationsAsync().then((token: any) => {
      global.token = token;
      console.log("====================================");
      console.log(token);
      console.log("====================================");
    });
    notificationListener.current =
      Notifications.addNotificationReceivedListener((notification) => {
        // alert();
      });
    responseListener.current =
      Notifications.addNotificationResponseReceivedListener((response) => {
        debugger;
        console.log("response", response);
      });
    return () => {
      Notifications.removeNotificationSubscription(
        notificationListener.current
      );
      // sendPushNotification(expoPushToken);
      Notifications.removeNotificationSubscription(responseListener.current);
    };
  }, []);

这样就完成了,用起来十分便捷

服务器端
image.png
expo服务器已经集成好了相关的服务,可以直接调用,当然expo也提供了服务器端的相关sdk可以自定义集成。这里客户使用的是直接用expo,所以这里只说下直接用expo怎么用:
直接 POST request https://exp.host/--/api/v2/push/send header信息如下:
host: exp.host
accept: application/json
accept-encoding: gzip, deflate
content-type: application/json

测试命令:

curl -H "Content-Type: application/json" -X POST "https://exp.host/--/api/v2/push/send" -d '{
  "to": "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
  "title":"hello",
  "body": "world"
}'

rn调用推送代码:

function sendPushNotification(title: string, message: string) {
  const message1 = {
    to: global.token,
    sound: "default",
    title: title,
    body: message,
    data: { someData: "goes here" },
  };

  fetch("https://exp.host/--/api/v2/push/send", {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Accept-encoding": "gzip, deflate",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(message1),
  });
}

异常

如果运行过程中出现异常:

"{"errors":[{"code":"VALIDATION_ERROR","message":"The Expo push notification service is supported only for Expo projects. Ensure you are logged in to your Expo developer account on the computer from which you are loading your project.","isTransient":false}]}"

需要打开控制台,登录expo账号


image.png

相关文章

  • expo react-native 消息推送

    今天有个巴基斯坦友人求助expo消息推送,之前国内一直用极光之类,所以类似expo推送之前还真没接触过,对方把项目...

  • React-Native 消息推送

    在这里我们可以选择大厂的推送,优先使用极光推送,下一篇将介绍如何使用阿里推送。 使用说明 PS: 真没想到极光大厂...

  • react-native 消息推送

    ios新建推送以及开发证书部分(略去) 创建私钥 Strip anything outside of "-----...

  • React-Native 消息推送--Android混合推送

    背景 由于使用任何一种Android推送都很难在APP进程被杀死后收到推送,只有集成各厂商提供的系统级别推送才能完...

  • react native - navigaiton

    环境要求 react-native>= 0.63.0 expo>= 41(如果您使用世博会[https://exp...

  • Android - React-native在原生MainAct

    React-native在MainActivity中发送消息给前端 目前,一些App都会集成推送的功能,很多需求中...

  • react-native Expo 下载

    reactNative开发工具 Expo自行下载:Chrome插件下载(需要梯子翻墙)1、下载Chrome插件AP...

  • react-native 打包流程

    问题 react-native方便了移动端app组件的开发,但是其社区以来的expo jdk 在某些业务场景下不足...

  • expo开发React-Native方式对比

    其实文章一开始想叫如何下载React-Native开发工具------EXPO XDE,但是扩充得多了,索性改全面...

  • React-Native安装、创建项目

    一:安装React-native的两种方式: 1:react-native-cli 2:expo-cli 第一种安...

网友评论

      本文标题:expo react-native 消息推送

      本文链接:https://www.haomeiwen.com/subject/idjceltx.html