React Native 使用亚马逊 SNS 进行推送通知

huangapple go评论72阅读模式
英文:

React Native Push Notification with Amazon SNS

问题

请问有人可以指导我如何在React Native项目中使用Amazon SNS实现推送通知的代码库或教程?

我已经在文档上苦苦挣扎了一周。我可以在Amazon SNS中注册设备,但无法接收消息。任何帮助将不胜感激。

我的所有代码都在App.js中。提前感谢!

import { StatusBar } from "expo-status-bar";
import { useEffect } from "react";
import { StyleSheet, Text, View, Platform } from "react-native";
import AWS from "aws-sdk";
import * as Notifications from "expo-notifications";
import {
  AWS_ACCESS_KEY,
  AWS_SECRET_ACCESS_KEY,
  REGION,
  TOPIC_ARN,
  PLATFORM_ARN,
  IOS_PLATFORM_ARN,
  EXPO_PROJECT_ID,
} from "@env";
export default function App() {
  useEffect(() => {
    // 请求权限以接收通知
    const requestUserPermission = async () => {
      const { status } = await Notifications.requestPermissionsAsync();
      if (status !== "granted") {
        console.log("Permission to receive notifications was denied.");
      }
    };
    // 使用AWS SNS注册设备令牌
    const registerDeviceTokenWithSNS = async () => {
      try {
        const deviceToken = (
          await Notifications.getExpoPushTokenAsync({
            projectId: EXPO_PROJECT_ID,
          })
        ).data;
        // 配置AWS SDK
        AWS.config.update({
          region: REGION,
          accessKeyId: AWS_ACCESS_KEY,
          secretAccessKey: AWS_SECRET_ACCESS_KEY,
        });
        const SNS = new AWS.SNS({ correctClockSkew: true });
        const platformApplicationArn = PLATFORM_ARN; // AWS SNS中您的平台应用程序的ARN
        // 创建平台端点并订阅主题
        const endpointParams = {
          PlatformApplicationArn: platformApplicationArn,
          Token: deviceToken,
        };
        const createEndpointResponse = await SNS.createPlatformEndpoint(
          endpointParams
        ).promise();
        const endpointArn = createEndpointResponse.EndpointArn;
        const subscribeParams = {
          TopicArn: TOPIC_ARN, // 您要订阅的主题的ARN
          Protocol: "Application",
          Endpoint: endpointArn,
        };
        await SNS.subscribe(subscribeParams).promise();
        console.log("成功注册设备到AWS SNS。");
      } catch (error) {
        console.log("无法注册设备到AWS SNS:", error);
      }
    };
    requestUserPermission();
    registerDeviceTokenWithSNS();
  }, []);
  return (
    <View style={styles.container}>
      <Text>AWS SNS演示</Text>
      <StatusBar style="auto" />
    </View>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});
英文:

Can someone point me in the direction of a codebase or tutorial that shows you how to implement Push Notification in a React Native project using Amazon SNS?

I've been struggling with the documentation for about a week. Im able to register devices within Amazon SNS but messages are not being received. Any help would be greatly appreciated.

All my code is in App.js. Thanks in advance!

    import { StatusBar } from &quot;expo-status-bar&quot;;
import { useEffect } from &quot;react&quot;;
import { StyleSheet, Text, View, Platform } from &quot;react-native&quot;;
import AWS from &quot;aws-sdk&quot;;
import * as Notifications from &quot;expo-notifications&quot;;
import {
AWS_ACCESS_KEY,
AWS_SECRET_ACCESS_KEY,
REGION,
TOPIC_ARN,
PLATFORM_ARN,
IOS_PLATFORM_ARN,
EXPO_PROJECT_ID,
} from &quot;@env&quot;;
export default function App() {
useEffect(() =&gt; {
// Request permission to receive notifications
const requestUserPermission = async () =&gt; {
const { status } = await Notifications.requestPermissionsAsync();
if (status !== &quot;granted&quot;) {
console.log(&quot;Permission to receive notifications was denied.&quot;);
}
};
// Register device token with AWS SNS
const registerDeviceTokenWithSNS = async () =&gt; {
try {
const deviceToken = (
await Notifications.getExpoPushTokenAsync({
projectId: EXPO_PROJECT_ID,
})
).data;
// Configure AWS SDK
AWS.config.update({
region: REGION,
accessKeyId: AWS_ACCESS_KEY,
secretAccessKey: AWS_SECRET_ACCESS_KEY,
});
const SNS = new AWS.SNS({ correctClockSkew: true });
const platformApplicationArn = PLATFORM_ARN; // ARN of your platform application in AWS SNS
// Create platform endpoint and subscribe to topic
const endpointParams = {
PlatformApplicationArn: platformApplicationArn,
Token: deviceToken,
};
const createEndpointResponse = await SNS.createPlatformEndpoint(
endpointParams
).promise();
const endpointArn = createEndpointResponse.EndpointArn;
const subscribeParams = {
TopicArn: TOPIC_ARN, // ARN of the topic you want to subscribe to
Protocol: &quot;Application&quot;,
Endpoint: endpointArn,
};
await SNS.subscribe(subscribeParams).promise();
console.log(&quot;Successfully registered device with AWS SNS.&quot;);
} catch (error) {
console.log(&quot;Failed to register device with AWS SNS:&quot;, error);
}
};
requestUserPermission();
registerDeviceTokenWithSNS();
}, []);
return (
&lt;View style={styles.container}&gt; &lt;Text&gt;AWS SNS Demo&lt;/Text&gt; &lt;StatusBar style=&quot;auto&quot; /&gt; &lt;/View&gt; ); } const styles = StyleSheet.*create*({ container: { flex: 1, backgroundColor: &quot;#fff&quot;, alignItems: &quot;center&quot;, justifyContent: &quot;center&quot;, }, });

答案1

得分: 0

我已经能够自己解决这个问题。我没有意识到的是,为了使Amazon SNS正常工作,您必须在实际设备上至少运行一个开发版本。一旦我构建了我所需要的Android和iOS的apk和ipa文件,它就可以正常工作。如果有人需要在React Native中使用Amazon SNS的帮助,请回复此消息,我会尽力提供帮助。

英文:

I have been able to figure this out on my own. What I didn't realize is that in order to get Amazon SNS to work you have to be running at least a development build on your actual device. Once I built the apk and ipa files that I needed for android and ios it worked. If anyone needs help with Amazon SNS with React Native just reply to this and I will try to help.

huangapple
  • 本文由 发表于 2023年6月29日 04:43:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76576590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定