Send push notifications to an iOS app with Java and AWS Lambda

Introduction

Introduction

Pusher Beams allows you to customize push notifications you send to your devices via a server. However it can be expensive to run a server 24 hours a day 7 days a week and we may only need to send notifications every so often. This is where AWS Lambda can help. Lambda functions are serverless and work on a pay as you go model (with a generous free tier). This means that you only pay for when you use the function. We’re going to explore how we can setup Pusher Beams on an iOS client using an AWS Lambda function running Java to trigger the notifications.

Prerequisites

Create your Lambda function

Creating a Pusher Beams instance

Log in or create your Pusher account to access the dashboard and create a new Pusher Beams instance.

aws-java-ios-lambda-1

Complete step one of the iOS setup guide, by providing your APNS key and team ID and clicking Continue. We will pick up the remainder later on in this tutorial. Press the X to exit the setup guide and you will be returned to your dashboard for that instance. Scroll to the bottom of the page and you will find your Pusher Beams instance ID and secret key, make note of these you will need them later.

Writing our function

Open your Eclipse IDE and press CMD + N this will open the new project wizard. Expand the AWS folder (make sure you have the AWS Toolkit installed if you don’t see this) and select AWS Lambda Java Project and click Next.

In the next window provide a Project name, Group ID, Artifact ID and Class Name. You may leave these as the default if you wish. For the Input Type, choose Custom, to complete the set up select Finish.

aws-java-ios-lambda-2

Once the project has finished setting up open the pom.xml. Add the following within your dependencies:

1// pom.xml
2    <dependencies>
3      ...
4      <dependency>
5          <groupId>com.pusher</groupId>
6          <artifactId>push-notifications-server-java</artifactId>
7          <version>1.1.0</version>
8      </dependency>
9      ...
10    </dependencies>

Create a new file in the lambda package called RequestClass.java. Within this file add the following:

1// src/main/java/RequestClass.java
2    package com.amazonaws.lambda.demo;
3    
4    public class RequestClass {
5            String title;
6            String message;
7            
8            public String getTitle() {
9                    return title;
10            }
11            
12            public void setTitle(String title) {
13                    this.title = title;
14            }
15            
16            public String getMessage() {
17                    return message;
18            }
19            
20            public void setMessage(String message) {
21                    this.message = message;
22            }
23             
24            public RequestClass(String title, String message) {
25                    this.title = title;
26                    this.message = message;
27            }
28            
29            public RequestClass() {
30            }
31    }

This code will be used by our Lambda function in order to parse the data we will pass in to the function to create our push message. Next open your LambdaFunctionHandler.java and replace the contents with:

1// src/main/java/RequestClass.java
2    package com.amazonaws.lambda.demo;
3    
4    import java.util.List;
5    import java.io.IOException;
6    import java.net.URISyntaxException;
7    import java.util.ArrayList;
8    import java.util.Arrays;
9    import java.util.HashMap;
10    import java.util.Map;
11    import com.amazonaws.services.lambda.runtime.Context;
12    import com.amazonaws.services.lambda.runtime.RequestHandler;
13    import com.pusher.pushnotifications.PushNotifications;
14    
15    public class LambdaFunctionHandler implements RequestHandler<RequestClass, String> {
16    
17        @Override
18        public String handleRequest(RequestClass request, Context context) {
19            String instanceId = "YOUR_INSTANCE_ID";
20            String secretKey = "YOUR_SECRET_KEY";
21    
22            PushNotifications beamsClient = new PushNotifications(instanceId, secretKey);
23            List<String> interests = Arrays.asList("hello");
24    
25            Map<String, Map> publishRequest = new HashMap();
26            Map<String, String> alertMessage= new HashMap();
27            alertMessage.put("title", request.title);
28            alertMessage.put("body", request.message);
29            
30            Map<String, Map> alert = new HashMap();
31            alert.put("alert", alertMessage);
32            
33            Map<String, Map> aps = new HashMap();
34            aps.put("aps", alert);
35            publishRequest.put("apns", aps);
36    
37            try {
38              beamsClient.publishToInterests(interests, publishRequest);
39              return "Push sent!";
40            } catch (IOException e) {
41              e.printStackTrace();
42              return "Push failed!";
43            } catch (InterruptedException e) {
44              e.printStackTrace();
45              return "Push failed!";
46            } catch (URISyntaxException e) {
47              e.printStackTrace();
48              return "Push failed!";
49            }
50    
51        }
52    }

This code will be used by our Lambda function later on to publish notifications to devices that are registered for the hello interest. We use the request.title and request.message to form part of the APNS notification. We’ll look at this in more detail when we come to test our integration. Remember to replace YOUR_INSTANCE_ID and YOUR_SECRET_KEY with the credentials from your Pusher Beams console.

Deploy your code

Right click in the eclipse editor select AWS Lambda → Upload function to AWS Lambda.

aws-java-ios-lambda-3

On the next screen select a IAM role if you have one. If you don’t use the Create button to make a new one and call it “lambda_basic_execution”. Next, we would need to create a bucket on the AWS console. If we don’t already have one. Make sure that there are permissions to the root user. And lastly but most importantly make sure that the user created initially has all of the permissions required - AmazonS3FullAcces. Leave everything else the same and click Finish to upload your code to AWS Lambda.

Note: Always make sure the bucket region matches the Lambda target region.

Create your iOS application

Now that we have created our Lambda function, we need to have a user that has actually registered for notifications and signed up for the hello interest so we can test out our implementation. We’re going to create a very basic app that doesn’t actually show anything to the user except for the notification on the lock screen.

Project setup

Create a new Single View App using Xcode and name it something like LambdaPush. Once the project is created we need to install the Beams SDK. Open the terminal and go to the working directory of the newly created project and run the following command.

    $ pod init

Open the newly created Podfile and add the following pod:

    pod 'PushNotifications'

In the terminal run:

    $ pod install

Make sure you close your Xcode project and reopen the newly created Xcode Workspace before continuing. Within your project capabilities make sure you have switched on the Push Notifications capability. Also turn on the Background Modes capability and tick the box for Remote Notifications.

Open your AppDelegate.swift file and replace its contents with the following. Remembering to replace the instance ID with your own.

1// AppDelegate.swift
2    import UIKit
3    import PushNotifications
4    
5    @UIApplicationMain
6    class AppDelegate: UIResponder, UIApplicationDelegate {
7        var window: UIWindow?
8        let pushNotifications = PushNotifications.shared
9    
10        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
11            self.pushNotifications.start(instanceId: "YOUR_INSTANCE_ID")
12            self.pushNotifications.registerForRemoteNotifications()
13            try? self.pushNotifications.subscribe(interest: "hello")
14    
15            return true
16        }
17    
18        func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
19            self.pushNotifications.registerDeviceToken(deviceToken)
20        }
21    
22        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
23            self.pushNotifications.handleNotification(userInfo: userInfo)
24        }
25    }

You can now run the application on your iOS device and accept to receive notifications. The SDK will then manage registering our interest in hello. Remember to replace YOUR_INSTANCE_ID with your instance ID credential from your Pusher Beams console.

Testing our implementation

Return to your Lambda function code in the Eclipse IDE. Right-click and select AWS Lambda → Run function on AWS Lambda. A dialog box will appear, make sure your lambda function is selected from the dropdown list and that the Enter the JSON input for your function radio button is selected. In text field provided add the following:

    {"title": "hello", "message": "Just a friendly hello"}  

Notice how our keys in the JSON object are title and message. These are the event keys we were using in our code to provide the title and body for the push notification.

aws-java-ios-lambda-4

If everything has worked as expected you should receive a push to your device and a similar log output from your Lambda console.

aws-java-ios-lambda-5

Note: You can also test your integration directly from the AWS Lambda console. A function will have been created there for you.

Conclusion

We’ve learnt how to create an AWS Lambda function using Java that can publish a push notification using Pusher Beams to an iOS device. The source code for this tutorial can be found here.