Omnichannel Services – Send Push Notifications to iOS Devices

Today I’m going to show you how to create an omnichannel service that send push notifications to iOS devices like iPhone and iPad. This an important feature in any app as it allows the user to be made aware of any important updates.

To make push notifications work, you first need to be a paid member in Apple’s iOS Developer Program. When you are, you can go to the developer portal and create an app (ID), a push notification certificate (1), and a provisioning profile (2). I won’t go through this here, but you find the details on Apple’s developer site. Please note that to use the certificate and private key with PHP, you need to convert them to .pem format. With the provisioning profile added, the app will register with the Apple Push Notification Service (APNS) on each run (3), and will get a device token in return (4). That token is normally shared with an omnichannel service (5), to be used when sending push notifications to the specific device. When something happens in the back-end (6), the service is either notified or has to poll, and sends a push notification message to the APNS (7). The APNS sends it to the device, which usually forwards it to the app (8), and the app then typically requests new information from the service (9).

Let’s have a look at the third and fourth steps of this process, and this is the code in the app’s delegate class…

…and on startup, the app registers with the APNS (line 3). Then, it waits for either an event with the device token (lines 6-10) or an error event (lines 11-14).

Now it’s time to create a service that sends a push notification, and even if I’m using PHP, the same functionality can be achieved on all major platforms, like those from IBM and Microsoft…

…and first a stream context is created with the certificate and its passphrase (line 2-4), which is used to open a socket to the APNS (line 5). If the APNS responds (checked on line 6), the device token (line 10) and message (line 11) is set, and the push notification payload is created (line 12) as JSON (line 13). The message to the APNS is set up (line 14) and sent (line 15). A message is showing whether it went well (line 17 or 21) and the socket is closed (line 23). To deploy this code to a cloud server, please see my previous videos.

This is actually all you need to do to receive a push notification if the device is on the lock screen, but if the app is in the foreground or background, and you want to show an alert, you need to add some more code to the app delegate class…

…and the first chunk of code (line 1-9) get the push notification while starting the app (in didFinishLaunchingWithOptions), and the second while it’s in foreground or background (line 10-14). They both call the third (line 15-20) that show an alert with the pushed message and reset the badge.

There you have an omnichannel service that sends push notifications to iOS devices.