使用 Amazon 软件开发工具包订阅 Amazon SNS 主题的移动应用程序 - Amazon Simple Notification Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

使用 Amazon 软件开发工具包订阅 Amazon SNS 主题的移动应用程序

以下代码示例展示如何订阅移动应用程序终端节点,以接收来自 Amazon SNS 主题的通知。

C++
SDK for C++

/** * Subscribe an app endpoint to a topic - demonstrates how to initiate a subscription to an Amazon SNS topic * with delivery to a mobile app. * * NOTE: You must first create an endpoint by registering an app and device. * See https://docs.aws.amazon.com/sns/latest/dg/mobile-push-send-devicetoken.html for more information. * * <protocol_value> set to "application" provides delivery of JSON-encoded message to an EndpointArn * for a mobile app and device (see https://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html for available protocols). * <topic_arn_value> can be obtained from run_list_topics executable and includes the "arn:" prefix. * <mobile_endpoint_arn> is the EndpointArn of a mobile app and device. */ int main(int argc, char ** argv) { if (argc != 4) { std::cout << "Usage: subscribe_app <protocol_value/application> <topic_arn_value>" " <mobile_endpoint_arn>" << std::endl; return 1; } Aws::SDKOptions options; Aws::InitAPI(options); { Aws::SNS::SNSClient sns; Aws::String protocol = argv[1]; Aws::String topic_arn = argv[2]; Aws::String endpoint = argv[3]; Aws::SNS::Model::SubscribeRequest s_req; s_req.SetTopicArn(topic_arn); s_req.SetProtocol(protocol); s_req.SetEndpoint(endpoint); auto s_out = sns.Subscribe(s_req); if (s_out.IsSuccess()) { std::cout << "Subscribed successfully " << std::endl; } else { std::cout << "Error while subscribing " << s_out.GetError().GetMessage() << std::endl; } } Aws::ShutdownAPI(options); return 0; }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for C++ API 参考中的 Subscribe

JavaScript
SDK for JavaScript V3

在单独的模块中创建客户端并将其导出。

import { SNSClient } from "@aws-sdk/client-sns"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SNS service object. const snsClient = new SNSClient({ region: REGION }); export { snsClient };

导入开发工具包和客户端模块,然后调用 API。

// Import required AWS SDK clients and commands for Node.js import {SubscribeCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; // Set the parameters const params = { Protocol: "application" /* required */, TopicArn: "TOPIC_ARN", //TOPIC_ARN Endpoint: "MOBILE_ENDPOINT_ARN", // MOBILE_ENDPOINT_ARN }; const run = async () => { try { const data = await snsClient.send(new SubscribeCommand(params)); console.log("Success.", data); return data; // For unit tests. } catch (err) { console.log("Error", err.stack); } }; run();

有关 Amazon 开发工具包开发人员指南和代码示例的完整列表,包括帮助入门和有关早期版本的信息,请参阅 将 Amazon SNS 与 Amazon 开发工具包结合使用