AMAZON AWS How do i subscribe an endpoint to SNS topic?

耗尽温柔 提交于 2019-11-28 18:54:05

There is no way to automatically subscribe an endpoint to a topic, but you can accomplish all through code.

You can directly call the Subscribe API after you have created your endpoint. Unlike other kinds of subscription, no confirmation is necessary with SNS Mobile Push.

Here is some example Objective-C code that creates an endpoint and subscribes it to a topic:

AWSSNS *sns = [AWSSNS defaultSNS];
AWSSNSCreatePlatformEndpointInput *endpointRequest = [AWSSNSCreatePlatformEndpointInput new];
endpointRequest.platformApplicationArn = MY_PLATFORM_ARN;
endpointRequest.token = MY_TOKEN;

[[[sns createPlatformEndpoint:endpointRequest] continueWithSuccessBlock:^id(AWSTask *task) {
    AWSSNSCreateEndpointResponse *response = task.result;

    AWSSNSSubscribeInput *subscribeRequest = [AWSSNSSubscribeInput new];
    subscribeRequest.endpoint = response.endpointArn;
    subscribeRequest.protocols = @"application";
    subscribeRequest.topicArn = MY_TOPIC_ARN;
    return [sns subscribe:subscribeRequest];
}] continueWithBlock:^id(BFTask *task) {
    if (task.cancelled) {
        NSLog(@"Task cancelled");
    }
    else if (task.error) {
        NSLog(@"Error occurred: [%@]", task.error);
    }
    else {
        NSLog(@"Success");
    }
    return nil;
}];

Make sure you have granted access to sns:Subscribe in your Cognito roles to allow your application to make this call.

Update 2015-07-08: Updated to reflect AWS iOS SDK 2.2.0+

This is the original code to subscribe an endpoint to a topic in Swift3

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    //Get Token ENDPOINT
    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})

    //Create SNS Module
    let sns = AWSSNS.default()
    let request = AWSSNSCreatePlatformEndpointInput()
    request?.token = deviceTokenString

    //Send Request
    request?.platformApplicationArn = Constants.SNSDEVApplicationARN

    sns.createPlatformEndpoint(request!).continue({ (task: AWSTask!) -> AnyObject! in
        if task.error != nil {
            print("Error: \(task.error)")
        } else {

            let createEndpointResponse = task.result! as AWSSNSCreateEndpointResponse
            print("endpointArn: \(createEndpointResponse.endpointArn)")

            let subscription = Constants.SNSEndPoint //Use your own topic endpoint

            //Create Subscription request
            let subscriptionRequest = AWSSNSSubscribeInput()


              subscriptionRequest?.protocols = "application"
                subscriptionRequest?.topicArn = subscription
                subscriptionRequest?.endpoint = createEndpointResponse.endpointArn

                sns.subscribe(subscriptionRequest!).continue ({
                    (task:AWSTask) -> AnyObject! in
                    if task.error != nil
                    {
                        print("Error subscribing: \(task.error)")
                        return nil
                    }

                    print("Subscribed succesfully")

                   //Confirm subscription
                    let subscriptionConfirmInput = AWSSNSConfirmSubscriptionInput()
                    subscriptionConfirmInput?.token = createEndpointResponse.endpointArn
                    subscriptionConfirmInput?.topicArn = subscription
                    sns.confirmSubscription(subscriptionConfirmInput!).continue ({
                        (task:AWSTask) -> AnyObject! in
                        if task.error != nil
                        {
                            print("Error subscribing: \(task.error)")
                        }
                        return nil
                    })
                    return nil

                })

            }
            return nil

        })
    }

If you want to use static credentials instead of using AWSCognito you will need to create those through Amazons IAM console.

Here is the code for initializing the Amazon in your App Delegate

    // Sets up the AWS Mobile SDK for iOS
    // Initialize the Amazon credentials provider
    AWSStaticCredentialsProvider *credentialsProvider =[[AWSStaticCredentialsProvider alloc] initWithAccessKey:AWSAccessID secretKey:AWSSecretKey];

    AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:DefaultServiceRegionType credentialsProvider:credentialsProvider];

    [AWSServiceManager defaultServiceManager].defaultServiceConfiguration = configuration;

Fissh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!