Send push notifications to iOS from an Azure function running NodeJS

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 Microsoft Azure Functions can help. Azure 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 Azure Function running NodeJS to trigger the notifications.

Prerequisites

Create your Azure function

Creating a Pusher Beams instance

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

NodeJS-azure-beams-notifications-img1

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.

Creating our function

Log in to your Microsoft Azure portal. Using the search facility (found at the top of the page) search for “Function App”.

Note: When searching make sure to sure for “Function App” and not “Function Apps”

Once you are on the function app page click Add to begin the process of adding a new Azure Function. You will need to give your app a name, this must be unique and you cannot use full stops. Try reverse domain naming like this: com-example-appname. I have used PusherBeams-NodeJS-iOS. As long as the radio buttons are set to Create new, entering a name should also auto complete the resource group and storage. If it hasn’t you should complete these fields as well.

Select your Subscription and Hosting Plan. If you’re unsure what these should be leave them as the default values. We will also be using Windows OS for this tutorial and our location will be set to Central US. However feel free to alter the location if the JavaScript run time is available there as well. Make sure your Runtime Stack is set to JavaScript and click Create.

NodeJS-azure-beams-notifications-img2

Note: Whilst we are using the Windows OS for this tutorial you may also be able to follow using the Linux OS. If you are doing this please select the Publish option as Code and be aware that there may be some unforeseen differences in the remainder of this tutorial.

Once your resource has been created you should receive a notification on the navigation bar. If you don’t see this, wait a couple of minutes and refresh the page. Your resource should appear in a list of Function Apps. Select your resource.

Now you have created a Function App you need to create a Function. On the overview page select the button New Function or from the side bar click on the + the is next to the Functions drop down. You will be given a selection of ways to build your function, select the In-portal option and click Continue.

Azure functions make it easy to invoke your code by hitting an HTTP endpoint. This is great for push notifications, as you can hit this endpoint using our HTTP rest client and passing in our message. You will see more of this later when you test your integration. For now select the Webhook + API option and click Create.

Note: There are lots of other templates available for invoking your function and you may wish to explore these as well. You can always invoke your function from the portal if you wish to.

Writing our function

The first thing we need to do in our function is install our dependencies. Azure makes this really simple for us by providing us a console. At the bottom of your screen you should see an option Console, click it to expand the console and enter the following:

    $ npm install @pusher/push-notifications-server

Your index.js file should be open in the main text editor. If it isn’t you can select it by expanding the Files section on the right and clicking it, add the following code to index.js:

1// index.js
2    module.exports = async function (context, req) {
3      const PushNotifications = require('@pusher/push-notifications-server');
4      let beamsClient = new PushNotifications({
5        instanceId: 'YOUR_INSTANCE_ID',
6        secretKey: 'YOUR_SECRET_KEY'
7      });
8      beamsClient.publishToInterests(['hello'], {
9        apns: {
10          aps: {
11            "alert" : {
12              "title" : req.body.title,
13              "body" : req.body.message
14            },
15          }
16        }
17      }).then((publishResponse) => {
18         context(done);
19      }).catch((error) => {
20        console.log(error);
21        context(done);
22      });
23    };

Note: Make sure not to leave any whitespace at the top of your function. This can cause unknown errors to occur.

This code will be used by our Azure function later on to publish notifications to devices that our registered for the hello interest. We use the event.title and event.message to form part of the message. 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.

At the top of your text editor you should see a Get function URL button, click this and copy the URL for the default (Function key) and keep it somewhere safe. You will need it for testing your integration later on.

NodeJS-azure-beams-notifications-img3

Create your iOS application

Now that we have created our Azure 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 AzurePush. 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', '2.0.0'

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.addDeviceInterest(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

Open your Postman HTTP rest client and create a new POST request. Add the function URL, that you got from your Azure function earlier, to the URL field. This URL contains a secret key for invoking your function, anybody with this key could potentially invoke your function so you should not share it within the public domain. Within the body of the post request add the following:

1{
2        "title": "hello",
3        "message": "Just a friendly hello"
4    }
NodeJS-azure-beams-notifications-img4

Once you are done press the Send button at the bottom. If everything has worked as expected you should receive a push to your device.

NodeJS-azure-beams-notifications-img5

Conclusion

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