Experience sending Apple Push Notification through SNS service from Amazon and some useful code

a Warm summer evening, in the process of developing another iOS app, I got two factors — the need arose to implement Apple Push Notification (APN) and the desire to try something completely new to me. To go the easy way via one of many services that offers sending APN is not wanted.

For the invention of the Bicycle was selected Amazon Simple Notification Service (Amazon SNS). Amazon SNS is a service that allows you to send messages notifications, through a variety of mechanisms (APN, GCM, e-mail, SMS, etc.).

About how it works and more detailed information can be found in documentation Amazon. I will tell you quite a bit to decide on the terminology. At SNS has two types of clients — publishers (publishers) and subscribers (subscribers). Publishers to subscribers asynchronously exchange messages (messages) that are delivered to subscribers through a variety of mechanisms. For sending group messages subscribers can be grouped by themes (topics). Then all the subscribers subscribed to the topic will receive the message in the subject sent.

Picture from the Amazon documentation:
image

Since the topic of this article is working with SNS of iOS, details on the backend are not going to stop. I will say a few sentences.
In the framework of the invention of the Bicycle backend was written using the following technologies:

the
    the
  • Java 1.8;
  • the
  • Spring Boot 1.2.4;
  • the
  • 3.3 Maven;
  • the
  • AWS SDK for Java-1.10.1.

I am a programmer in Objective C/Swift, so all is good, including Java, I was in this project used we can say for the first time. The project PushSnsSender posted it on GitHub. Firstly, it may useful to someone; and secondly, would be very happy push requestm.

This code raises a web service that into your POST request:

{"topic": "arn:aws:sns:YOUR-TOPIC", "message": "Hooray!", "badge": 0, "sound": "bingbong.aiff", "isDebug": false }


Send APN “Hooray!” on SNS-topic “YOUR-TOPIC”.

Whatever it was, not for the backend I've started this article. The thing is that the subscription mechanism on top of the iOS app unfairly overlooked in the documentation of the Amazon, and on it I want to stop. Maybe someone it will save precious hours of time.

Before you start programming, in the AWS console you need to perform the following steps:

the
    the
  • activation of SNS AWS;
  • the
  • activate AWS Cognito;
  • the
  • creation of a Platform Application in SNS and bind the Apple keys to work with APN;
  • the
  • creation of new themes for the SNS;
  • the
  • create an Identity Pool and tied to it roles for Cognito service.

I'm not going to describe the steps above in order not to repeat a lot of already written articles. In addition, the documentation for each Amazon service is really very detailed and good to understand is easy. Will give a few screenshots for reference.

Window creation Platform Application:
image

Window create a new theme:
image

Window create a new Identity Pool:
image

A little late on the service Cognito. What is it and why is it needed?

As you know, with your cozy AWS should not be allowed to work for anyone. For strict authorization meets the AWS Identity and Access Management, each user grants authorization keys. Authorization keys, consisting of an Access Key Id and Secret Access Key is a very intimate thing, which, when ingested in the wrong hands can cause your AWS account and your wallet a lot of troubles. Therefore, never, under any circumstances don't get in cars with strangers uncles don't give the keys AWS.
Along with this, your iOS app on the phones of the users should authenticate to AWS, to subscribe to the topic. Here we come to the aid of the AWS Cognito — one of whose functions is the authentication of users and assign them a specific role. To use the service simply. After creating a new Identity Pool, the service itself will generate you a code which you can use in your iOS app.

the new Identity Pool, and the generated code:
image

Introductory operation is finished and you can finally move on to the favorite part — writing code.
To work with Amazon from our iOS app, we need the AWS SDK for iOS, but rather three components there: AWSCore; AWSSNS and AWSCognito. To install use favorite package Manager, e.g. for CocoaPods it will look like this:
pod 'AWSCore', '~ > 2.2'
pod 'AWSSNS', '~ > 2.2'
pod 'AWSCognito', '~ > 2.2'


It is time the most interesting response to the question: “How of our iOS app to subscribe to the SNS topic?” Documentation Amazon will offer us the solution in the form of registration to an individual device and send a message to him that the mass distribution is not suitable. Therefore, after the authorization using the code that was generated by the Cognito service, we just a call of the API of the SNS and subscribe to the theme manually.
The calling code is below:

the
- (void)subscribeToPushTopicWithDeviceToken:(NSData *)deviceToken 
{

AWSSNS *sns = [AWSSNS defaultSNS];

AWSSNSCreatePlatformEndpointInput *endpointRequest = [AWSSNSCreatePlatformEndpointInput new];

//get some device's IDs
NSString *userDeviceName = [[UIDevice currentDevice] name];
NSString *userDevicePlatform = [[UIDevice currentDevice] model];

//get SNS settings 
self.myPlatformApplicationArn = @"arn:aws:sns:us-east-1:XXXXXXXXXXXXX:app/APNS/XXXXXXXXXXXXX";
self.myTopicArn = @"arn:aws:sns:us-east-1:XXXXXXXXXXXXX:XXXXXXXXXXXXX";

endpointRequest.platformApplicationArn = self.myPlatformApplicationArn;
endpointRequest.token = [self deviceTokenAsString:deviceToken];
endpointRequest.customUserData = [NSString stringWithFormat:@"%@ - %@", userDevicePlatform, userDeviceName];

[[[sns createPlatformEndpoint:endpointRequest] continueWithSuccessBlock:^id(AWSTask *task) {

AWSSNSCreateEndpointResponse *response = task.result;

AWSSNSSubscribeInput *subscribeRequest = [AWSSNSSubscribeInput new];

subscribeRequest.endpoint = response.endpointArn;
subscribeRequest.protocols = @"application";
subscribeRequest.topicArn = self.myTopicArn;

return [sns subscribe:subscribeRequest];

}] continueWithBlock:^id(AWSTask *task) {

if (task.cancelled) {
NSLog(@"AWS SNS Task cancelled!");
}

else if (task.error) {
NSLog(@"%s file: %s line: %d - AWS SNS Error occurred: [%@]", __FUNCTION__, __FILE__, __LINE__, task.error);
}

else {
NSLog(@"AWS SNS Task Success.");
}

return nil;

}];

}

That's all. After the successful launch applications in the AWS console you will see one authorized device Identity Pool in the Cognito service and your device as a subscriber to the subject:

screen with the reflection of the device is subscribed to a topic:
image

Note the difference of the Apple keys to work with APN in the development environment and a production environment.

Files Objective C:

BGMAwsSnsProvider.h
BGMAwsSnsProvider.m

Thank you for your attention. I hope this article saved you any time and pushed to pay attention to such a wonderful service like Amazon SNS.
Article based on information from habrahabr.ru

Комментарии

Популярные сообщения из этого блога

Integration of PostgreSQL with MS SQL Server for those who want faster and deeper

Custom database queries in MODx Revolution

Google Web Mercator: a mixed coordinate system