Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Home
Daily Thoughts
Ionic
Stack Overflow
Books
About me
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Nikola Brežnjak blog - Tackling software development with a dose of humor
Ionic

Cordova plugin for VoIP push notifications

TL;DR

This plugin didn’t exist, so I made it – Cordova plugin for receiving VoIP push notifications on iOS 8.0+ only.

Installation

For Ionic:

ionic plugin add cordova-ios-voip-push

For Cordova:

cordova plugin add cordova-ios-voip-push

Usage

var push = VoIPPushNotification.init();

push.on('registration', function(data) {
    log("[Ionic] registration callback called");
    log(data);

    //data.deviceToken;
    //do something with the device token (probably save it to your backend service)
});

push.on('notification', function(data) {
    log("[Ionic] notification callback called");
    log(data);

    // do something based on received data
});

push.on('error', function(e) {
    log(e);
});

Please see the Ionic demo for the exact usage example.

Running the demo

Ionic setup

Clone this repo:

git clone https://github.com/Hitman666/cordova-ios-voip-push.git

CD into the cloned project and the Ionic demo project:

cd cordova-ios-voip-push && cd ionicDemo

Install the dependencies:

npm install && bower install

Install the platform and plugins (please note that this process may take a while to complete):

ionic state reset

Add the plugin (either one of three options would work):

ionic plugin add cordova-ios-voip-push

or

ionic plugin add ../thePlugin/VoIPPushNotification

or like this:

ionic plugin add https://github.com/Hitman666/cordova-ios-voip-push.git

Prepare the project:

ionic prepare ios

Open the project in XCode by going into platforms/ios and opening up the pluginTest.xcodeproj file.

XCode setup

If you don’t have an AppID and VoIP push certificate created in your Apple developer account, you can do so by following my instructions from the How to create a native iOS app that can receive VoIP push notifications tutorial.

Take your time to do that an then come back, I’ll wait.

To use the VoIP push in the app, you need to turn ON the Background Modes for your app and check few of the checkboxes:

Make sure you select the following options:

  • Audio, Airplay, and Picture in Picture
  • Voice over IP
  • Background fetch
  • Remote notifications

Next, you need to add PushKit framework to your project:

Also (yeah, I know, a lot of setup), you need to make sure that you set the appropriate Bundle Identifier. You should have read about this in the tutorial I linked above.

After you run the project, in the XCode console you should see

and on your device:

You can send VoIP pushes to yourself by editing the simplepush.php file (in the pushSendingScript folder from the Github repo). Just make sure you add your own device id that you’ll see show up on your phone. You have more options to send VoIP push, two of which you can read in the post linked few times above.

!TL;DR

Disclaimer:
This tutorial was inspired by the official phonegap-plugin-push plugin, and the fact that this kind of VoIP support didn’t exist. There were requests for it here, here and here. As well as on freelance sites like here, here – hehe, hope these guys will send some donations to my favorite charity if they end up using this now 😉

Also, I don’t ‘do’ ObjectiveC for a living (but I may change my mind after completing this :)), so I would really appreciate the constructive feedback in making this plugin better, so I look forward to your comments and potential pull requests!

In my previous tutorial I showed how to create a native iOS app with Swift (ObjectiveC code also available) that can receive VoIP push notifications sent with Houston, custom PHP script or through Amazon SNS.

In this tutorial I’m going to present to you the Cordova plugin that does the same thing; it allows hybrid iOS applications to receive the VoIP push notifications.

Building Cordova plugins

I won’t go into the details of Cordova plugin building in this document. If you’re new to building Cordova plugins, you can check out this tutorial and official docs, as they were indispensable in my quest to learn as much as possible about it.

plugin.xml

<?xml version='1.0' encoding='utf-8'?>
<plugin id="com.nikola-breznjak.voippush" version="1.0.0" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
    <name>VoIPPushNotification</name>
    <js-module name="VoIPPushNotification" src="www/VoIPPushNotification.js">
        <clobbers target="VoIPPushNotification" />
    </js-module>

    <platform name="ios">
        <config-file target="config.xml" parent="/*">
            <feature name="VoIPPushNotification">
                <param name="ios-package" value="VoIPPushNotification" />
            </feature>
        </config-file>

        <header-file src="src/ios/VoIPPushNotification.h" />
        <source-file src="src/ios/VoIPPushNotification.m" />
    </platform>
</plugin>

In this file you basically define:

  • for which platform is this plugin (<platform name="ios">)
  • where the source files of your plugin will be (header-file and source-file elements)
  • where is the JavaScript file that will be the bridge from Cordova to native code (js-module tag src property)
  • what will be the plugins name by which you’ll reference it in the Cordova/Ionic code (<clobbers target="VoIPPushNotification" />)

www/VoIPPushNotification.js

This file, stripped of it’s comments is very short (75 LOC):

var exec = cordova.require('cordova/exec');

var VoIPPushNotification = function() {
    this._handlers = {
        'registration': [],
        'notification': [],
        'error': []
    };

    // triggered on registration and notification
    var that = this;
    var success = function(result) {
        if (result && result.registration === 'true') {
            that.emit('registration', result);
        }
        else if (result) {
            that.emit('notification', result);
        }
    };

    // triggered on error
    var fail = function(msg) {
        var e = (typeof msg === 'string') ? new Error(msg) : msg;
        that.emit('error', e);
    };

    // wait at least one process tick to allow event subscriptions
    setTimeout(function() {
        exec(success, fail, 'VoIPPushNotification', 'init');
    }, 10);
};

VoIPPushNotification.prototype.on = function(eventName, callback) {
    if (this._handlers.hasOwnProperty(eventName)) {
        this._handlers[eventName].push(callback);
    }
};

VoIPPushNotification.prototype.off = function (eventName, handle) {
    if (this._handlers.hasOwnProperty(eventName)) {
        var handleIndex = this._handlers[eventName].indexOf(handle);
        if (handleIndex >= 0) {
            this._handlers[eventName].splice(handleIndex, 1);
        }
    }
};

VoIPPushNotification.prototype.emit = function() {
    var args = Array.prototype.slice.call(arguments);
    var eventName = args.shift();

    if (!this._handlers.hasOwnProperty(eventName)) {
        return false;
    }

    for (var i = 0, length = this._handlers[eventName].length; i < length; i++) {
        var callback = this._handlers[eventName][i];
        if (typeof callback === 'function') {
            callback.apply(undefined,args);
        } else {
            console.log('event handler: ' + eventName + ' must be a function');
        }
    }

    return true;
};


module.exports = {
    init: function(options) {
        return new VoIPPushNotification(options);
    },

    VoIPPushNotification: VoIPPushNotification
};

This code follows the structure of the phonegap-plugin-push push.js.

Once you call the init method, you get the new VoIPPushNotification object which then exposes the methods for listening to the registration, notification and error events.

src/ios/VoIPPushNotification.h

#import <Cordova/CDV.h>
#import <PushKit/PushKit.h>

@interface VoIPPushNotification : CDVPlugin <PKPushRegistryDelegate>

@property (nonatomic, copy) NSString *VoIPPushCallbackId;
- (void)init:(CDVInvokedUrlCommand*)command;

@end

Since we’re writing in ObjectiveC, we need to define the functions in the .h file. Here we do few things:

  • import Cordova and PushKit
  • add an instance property VoIPPushCallbackId
  • add an init function declaration

src/ios/VoIPPushNotification.m

#import "VoIPPushNotification.h"
#import <Cordova/CDV.h>

@implementation VoIPPushNotification

@synthesize VoIPPushCallbackId;

- (void)init:(CDVInvokedUrlCommand*)command
{
  self.VoIPPushCallbackId = command.callbackId;
  NSLog(@"[objC] callbackId: %@", self.VoIPPushCallbackId);

  //http://stackoverflow.com/questions/27245808/implement-pushkit-and-test-in-development-behavior/28562124#28562124
  PKPushRegistry *pushRegistry = [[PKPushRegistry alloc] initWithQueue:dispatch_get_main_queue()];
  pushRegistry.delegate = self;
  pushRegistry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];
}

- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type{
    if([credentials.token length] == 0) {
        NSLog(@"[objC] No device token!");
        return;
    }

    //http://stackoverflow.com/a/9372848/534755
    NSLog(@"[objC] Device token: %@", credentials.token);
    const unsigned *tokenBytes = [credentials.token bytes];
    NSString *sToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                         ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                         ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                         ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];

    NSMutableDictionary* results = [NSMutableDictionary dictionaryWithCapacity:2];
    [results setObject:sToken forKey:@"deviceToken"];
    [results setObject:@"true" forKey:@"registration"];

    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:results];
    [pluginResult setKeepCallback:[NSNumber numberWithBool:YES]]; //[pluginResult setKeepCallbackAsBool:YES];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:self.VoIPPushCallbackId];
}

- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(NSString *)type
{
    NSDictionary *payloadDict = payload.dictionaryPayload[@"aps"];
    NSLog(@"[objC] didReceiveIncomingPushWithPayload: %@", payloadDict);

    NSString *message = payloadDict[@"alert"];
    NSLog(@"[objC] received VoIP msg: %@", message);

    NSMutableDictionary* results = [NSMutableDictionary dictionaryWithCapacity:2];
    [results setObject:message forKey:@"function"];
    [results setObject:@"someOtherDataForField" forKey:@"someOtherField"];

    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:results];
    [pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:self.VoIPPushCallbackId];
}

@end

In the implementation file we define our functions. The first one is init, and here we basically register for VoIP push notifications by using PKPushRegistry.

Then, to satisfy that, we implement two functions: didUpdatePushCredentials and didReceiveIncomingPushWithPayload.

The first one is triggered with the device token, which we then send back to the ‘JS world’. We listen for this in our Ionic/Cordova apps and send this information to our backend so that later when we’re going to send the push we know to which device id.

The second one is triggered when we receive the actual VoIP push notification. In this example, we take out the message (@alert) and return it to the ‘JS world’. In my particular case, this can be a message with a certain keyword, so that then I know what to do in my app based on that keyword.

Again, I have to stress here that you may wanna alter this to your liking and process even more data which you receive through the VoIP push notification.

Conclusion

I hope this plugin will come handy to you. Also, I hope that this will give you enough information so that you’ll be dangerous enough to go and fiddle with the code yourself.

As I’ve mentioned before, I would really appreciate the constructive feedback so that we can make this plugin better, so I look forward to your comments and optional pull requests.

Btw, I updated these posts with this solution:

  • StackOverflow post
  • Ionic framework forum
  • phonegap-plugin-push plugin

and I have also asked the main maintainer of phonegap-plugin-push plugin if this would make sense to put as a PR on that plugin.

I will update you on the progress of all this, and till then – code on!

#Cordova plugin for #VoIP push notifications https://t.co/jkn56YWGTU

— Nikola Brežnjak (@HitmanHR) September 30, 2016

iOS

How to create a native iOS app that can receive VoIP push notifications

TL;DR

In this tutorial, I’ll give you step by step instructions on how to create a native iOS app with Swift (ObjectiveC code also available in the Github repo) that can receive VoIP push notifications sent with Houston, custom PHP script or through Amazon SNS.

This tutorial is largely inspired by this one (one of the few that actually made sense and made the steps manageable). However, I’ve added some not so obvious steps and fixed the issues that I had with the newest versions. Also, I added the link to the finished project on Github for further reference.

VoIP notifications

The official documentation can be found here. Few of the advantages are:

  • app is automatically relaunched if it’s not running when a VoIP push is received
  • device is woken up only when VoIP push occurs (saves battery)
  • VoIP pushes go straight to your app for processing and are delivered without delay
  • app is automatically relaunched if it’s not running when a VoIP push is received

Prerequisite settings

Apple provides us with a framework called PushKit to support using this VoIP push feature. However, we need to configure some additional settings to get this working.

Creating an App ID

In case you don’t already have an app (and consequently an App ID), you need to create one.

First, login to your Apple developer account and access Certificates, Identifier & Profiles:

Next, go to Identifiers->App IDs and then click on the + button.

Two important things to fill out here are App ID Description and so-called Bundle ID (this will most likely be something like com.yourdomain.yourappname):

Although not seen in the screenshots above, I used nikolaVoipTest as Bundle ID. This will be important in the next step.

Generating a VoIP push certificate

To generate a VoIP push certificate you first need to click on the All button in the Certificates section on the left-hand side. Then, click the + button:

On the next page you need to select the VoIP Services Certificate:

and on the one after that you need to select the App ID for which you’re creating this VoIP certificate:

Next, you’ll be presented with instructions on how to create a so-called CSR (Certificate Signing Request) file:

Once you create that file, you’ll select it for upload on the next screen. If everything goes well you’ll be given the certificate which you have to download:

After you download the certificate, open it up, and this should open the Keychain Access application, and you should see the certificate under the My Certificates section:

Creating the app

With all the setting out of our way, we can now start Xcode and create a new Single view application project:

Take special care when setting the Product Name as the Bundle Identifier is set automatically from it. We need to set this to be the same as the Bundle identifier that we’ve set in the steps above.

Setting the appropriate capabilities

To use the VoIP push in the app, we need to turn ON the Background Modes for our app and check few of the checkboxes:

Make sure you select the following options:

  • Audio, Airplay, and Picture in Picture
  • Voice over IP
  • Background fetch
  • Remote notifications

Adding the code

Open AppDelegate.swift and at the top add the import PushKit statement.

Then, in the didFinishLaunchingWithOptions part of the application function make sure you register for notifications like this:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        //Enable all notification type. VoIP Notifications don't present a UI but we will use this to show local nofications later
        let notificationSettings = UIUserNotificationSettings(forTypes: [.Badge, .Sound, .Alert], categories: nil)

        //register the notification settings
        application.registerUserNotificationSettings(notificationSettings)

        //output what state the app is in. This will be used to see when the app is started in the background
        NSLog("app launched with state \(application.applicationState)")

        return true
}

Since we are using the registerUserNotificationSettings method we need to implement it’s delegate callback application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings):

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {

    //register for voip notifications
    let voipRegistry = PKPushRegistry(queue: dispatch_get_main_queue())
    voipRegistry.desiredPushTypes = Set([PKPushTypeVoIP])
    voipRegistry.delegate = self;
}

In this callback, we register the VoIP notifications since we know that the user has agreed to receive notifications (since this function has been called). We enabled VoIP notifications by declaring the voipRegistry object.

At this point, you will get an error on the voipRegistry.delegate = self; line saying Cannot assign a value of type 'AppDelegate' to type 'PKPushRegistryDelegate!'.

The delegate for voipRegistry is of type PKPushRegistryDelegate which has three methods, two of which are required (didUpdatePushCredentials and didReceiveIncomingPushWithPayload). We have to define a so-called extension of the AppDelegate class. We do that by adding the following code after all the current code in the AppDelegate.swift file:

extension AppDelegate: PKPushRegistryDelegate {

    func pushRegistry(registry: PKPushRegistry!, didUpdatePushCredentials credentials: PKPushCredentials!, forType type: String!) {

        //print out the VoIP token. We will use this to test the notification.
        NSLog("voip token: \(credentials.token)")
    }

    func pushRegistry(registry: PKPushRegistry!, didReceiveIncomingPushWithPayload payload: PKPushPayload!, forType type: String!) {

        let payloadDict = payload.dictionaryPayload["aps"] as? Dictionary<String, String>
        let message = payloadDict?["alert"]

        //present a local notifcation to visually see when we are recieving a VoIP Notification
        if UIApplication.sharedApplication().applicationState == UIApplicationState.Background {

            let localNotification = UILocalNotification();
            localNotification.alertBody = message
            localNotification.applicationIconBadgeNumber = 1;
            localNotification.soundName = UILocalNotificationDefaultSoundName;

            UIApplication.sharedApplication().presentLocalNotificationNow(localNotification);
        }

        else {

            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                let alert = UIAlertView(title: "VoIP Notification", message: message, delegate: nil, cancelButtonTitle: "Ok");
                alert.show()
            })
        }

        NSLog("incoming voip notfication: \(payload.dictionaryPayload)")
    }

    func pushRegistry(registry: PKPushRegistry!, didInvalidatePushTokenForType type: String!) {

        NSLog("token invalidated")
    }
}

After adding this extension you will note that the previously mentioned error disappears.

In the first function, we merely output the device token. We will need this token in the next section when we’ll be testing our app with sending VoIP push notifications.

In the second one we ‘act’ on the received VoIP push notification. In this concrete case, we show a local notification if the app is in the background or an alert if we’re in the app. The third function (didInvalidatePushTokenForType) is used for handling when the token is invalidated.

Testing VoIP notifications

We have several options for testing our app. I’ll cover few of them in this section:

  • CLI program called Houston
  • PHP script called SimplePush
  • Amazon SNS

Getting the device token

Run your app in Xcode and make sure you run it on an actual device. The console output should look something like this:

2016-09-19 10:08:53.793
voipTestNikola[1876:2020432]
app launched with state UIApplicationState

2016-09-19 10:08:53.877
voipTestNikola[1876:2020432]
voip token: <40cc4209 d0f3ac25 95a7e937 3282897b 211231ef ba66764c 6fd2befa b42076cb>

Take note of the voip token from the output above (of course, the one from your Xcode debug window and not the one I’ve pasted above ;)), as we’ll need it in the next sections.

Preparing the certificate file

The VoIP certificate file that we’ve downloaded and added to the KeyChain has to be converted to a different file format so that we’ll be able to use it with the tools and services that I’ve listed above.

First, you need to open the KeyChain app on your Mac and then Export (Right click then select Export) the certificate:

You will get a .p12 file.

Now, navigate to the folder where you exported this file and execute the following command:

openssl pkcs12 -in YOUR_CERT.p12 -out VOIP.pem -nodes -clcerts

This will generate VOIP.pem file which we’ll use in the next sections.

Houston

Even though the docs say you can install it simply with gem install houston, you will most likely end up (after some StackOverflow searching) using this command to install it:

sudo gem install -n /usr/local/bin houston

This way you’ll install it to your local bin directory to which you have full rights.

Houston installed one more tool that will help us send the notifications like this:

With Terminal navigate to the folder where you have your certificate, copy the device id from above and execute a command like this:

apn push "<40cc4209 d0f3ac25 95a7e937 3282897b 211231ef ba66764c 6fd2befa b42076cb>" -c VOIP.pem -m "Testing VoIP notifications!"

Please note to change the VOIP.pem to whatever you named the file in the steps above.

You should get the following output in your terminal:

And, you should see this on your phone in case it was in the foreground:

In case the app was in the background you should see:

Also, I made a short video showcasing how the app behaves when it’s closed and receives a VoIP push (it’s woken up and run).

SimplePush

SimplePush (simplepush.php in the project root directory) is a PHP script that can be found on the net in few various forms and from few various authors. However, the code is less then 50 LOC, so it’s quite simple to understand. We need to set just a few of the config options:

// Put your device token here (without spaces):
$deviceToken = 'deviceToken';

// Put your private key's passphrase here:
$passphrase = 'passphrase';

// Put your alert message here:
$message = 'message';

// Put the full path to your .pem file
$pemFile = 'pemFile.pem';

and then run the script with php simplepush.php.

The only thing to note here is that we need to insert the device token without spaces and without < and > characters.

Amazon SNS

Amazon has really good documentation for preparing everything you need, and you can take a look at it here.

After you have all the prerequisites, you should follow these instructions to create the so-called ‘platform application’. Settings that I’ve used are on the image below:

After this you can add a platform endpoint by pasting your device id (again, as in the PHP example; without spaces and < and > characters).

Finally, you have to select this endpoint and click on the Publish to endpoint button:

Here you can enter some test data like shown below:

After you click on the Publish message you should get a notification on your phone.

Conclusion

In this tutorial you’ve learned how to create a native iOS app with Swift that can receive VoIP push notifications sent with Houston, custom PHP script or through Amazon SNS.

I bolded native for a reason in the sentence above. As you know, I’m a big fan of hybrid apps and Ionic framework in particular.

This post is a part of the recent task that I had to do to create the Cordova VoIP push plugin. To successfully complete that, I first made the native app and then the plugin, since (unfortunately) the plugin wasn’t available.

You can read all about how I created the Cordova plugin for receiving VoIP push notifications in this post.

How to create a #native #iOS app that can receive #VoIP push notifications https://t.co/PFGq7rqXZr

— Nikola Brežnjak (@HitmanHR) September 30, 2016

Recent posts

  • Discipline is also a talent
  • Play for the fun of it
  • The importance of failing
  • A fresh start
  • Perseverance

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (35)
  • Daily Thoughts (77)
  • Go (3)
  • iOS (5)
  • JavaScript (127)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (2)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (77)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (40)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak