Sending iOS Push Notifications via APNs
Tags: ios, swift, node, webdev
Published: 2021-10-04 11:46:05

---
title: Sending iOS Push Notifications via APNs
published: true
description: Need to iOS push notifications through APNs? Here’s a detailed blog that walks you through how to send push notifications with the help of a sample iOS.
tags: ios, swift, node, webdev
canonical_url: https://blog.engineyard.com/ios-push-notifications-via-apns?utm_source=dev.to&utm_medium=Devgraph-page&utm_campaign=canonical_url&utm_id=QiWorks.in
//cover_image: https://blog.engineyard.com/hs-fs/hubfs/jamie-street-33oxtOMk6Ac-unsplash.jpg?width=640&name=jamie-street-33oxtOMk6Ac-unsplash.jpg
---
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x8zl14bbmpqmbdsb9all.jpg)
By [Ritu Chaturvedi](https://blog.engineyard.com/author/ritu-chaturvedi)

User engagement is of the highest importance in today's world, no matter what you sell or offer to your clients. And mobile phone notifications play the masterstroke in this aspect. By regular interactions with your clients through push notifications, it is possible to release timely updates and stay connected with them. So, let us discuss setting up an Apple push notification service (APN) with a Node.js application today.

 

In this blog, we will discuss in detail the APN services, enable and register for remote notifications, device token ids, and APN node package with the help of a sample iOS. Make sure to have a physical iOS device, as push notifications won't work with the simulator. Also, an Apple Developer Program Membership account is a must for creating a Push Notifications Certificate.

## Getting to know about the Remote Notification Service

Apple devices use a remote notification service to send and receive notifications in any of the iOS, tvOS, or macOS. The remote notification setup is to be configured in your Apple device with proper device tokens and certificates. Otherwise, there are possibilities that the notification services don't work as expected.&nbsp;

The main component of this remote notification setup is the Apple Push Notification service, also known as APNs. APN in actuality is a collection of services that allows the developer to send the notifications from their server to the targeted iOS devices. The APNs are robust and secure methods to establish a connection between the provider server and individual Apple devices.&nbsp;

APN contains two components, the _Gateway component,_ and the _Feedback component,_ both of which are must-haves.&nbsp;

Gateway component establishes the TLS connection from a provider side which enables the provider server to send messages to the Apple, which will be processed by Apple and then forwarded to the respective device. It is recommended to keep the connection in an 'always-on' mode. The _Feedback Component_ is established only occasionally to identify and remove the devices which no longer receive notifications for specific applications. This is a mandatory component in any Apple device.

To receive and handle the remote notifications, the app you provide must have four components as basics. They are:

1. Remote connection enabled
2. A registered Apple Push Notification Service (APN) and device token
3. Sending device token to the notification provider
4. Establish support to handle incoming notifications in the device

Once the push notification setup is complete in your apps and the provider server-side, the providers can send notification requests to APNs. they convey the notification payloads to each targeted device. As the notification is received, the payload is delivered to the respective app and user communications are managed. It is great to note that the APNs hold the notifications if the device is powered off and waits till the device turns power on while trying multiple times to deliver the message to the appropriate app in the device. This makes it perfect for the user and the provider not to miss any important communication.

It is good to have a clear and strong [understanding of the APNs](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html#//apple_ref/doc/uid/TP40008194-CH8-SW1), direct from Apple’s guides.

The provider is entitled to many responsibilities. Some of the major ones are below:

- Receive globally unique, app-specific device tokens and all relevant data pertaining to your app on user’s devices.
- Determine when the remote notifications are to be sent to each device.
- Building and sending notification requests to APNs.

Only with proper entitlements to talk to APNs, can the app handle the remote notifications. Without these entitlements, the apps are rejected by the App Store. Know the details of entitlements required for your app in the [‘Enable push notification’](https://developer.apple.com/documentation/xcode) section of the Xcode Help page on Apple’s website. Once notification pushes are enabled, app registration is a must every time the app is launched. The process of app registering includes the below steps, for all Apple devices.

- Your app asks to be registered with APNs
- APNs sends app-specific device tokens
- The system delivers the device to your app by calling a method in your app delegate
- The device token is shared with the app’s associated provider&nbsp;

A method [registerForRemoteNotifications](https://developer.apple.com/documentation/uikit/uiapplication/1623078-registerforremotenotifications) is called at the launch time by your app. This initiates the app object to contact APN for app-specific device tokens. Below code shows how to fetch your device token:

![fetch your device token](https://lh6.googleusercontent.com/LKGo7PhKHC-qH2W3x9XQJD017qttXmcv5bHQ8Y2dtOThasw-yLZiTIWAvp98pyujpy_E6NMteiOdmMGA5Qi3l5f8BAPEbYNhjMhn0HP3Tz4y_2rLBflfqzRAAI3q7SgEzKNN5TA=s0)

Swift:&nbsp;

![how to fetch your device token](https://lh5.googleusercontent.com/9GZhmVgaIZNubrRSs9ZVtagRbQBZUqWZEkHcUHax4Yk6uE0zvuOLONNa6_WlAx12YxPekHr-Rvy5dn3crA1K6jeGJnV0zNe4hDC0TGakhROWvByUi5Smx4lUH5-N5FwdSMrO8lI=s0)

Know more about the [Remote and Local notifications](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/HandlingRemoteNotifications.html#//apple_ref/doc/uid/TP40008194-CH6-SW)on Apple’s page.

Thus, the system establishes an encrypted and persistent IP connection between the app and APNS, whenever the app starts on a device. This connection setups and enables the device to receive notifications, thus requires configuration on the Apple development account and necessary certificate creation.

For our servers to communicate with the APNs, a lot of connections and configurations are to be done in Node.js. It is easier to opt for the _apn_ packages with preset code to establish error-free connections. This ready-to-use package is one good choice for the production environment. The package is based on&nbsp; HTTP/2 API and is capable of maximizing the processing and notification delivery. It also collects the not-sent notifications when an error has occurred. The [official repository of the apn package](https://github.com/node-apn/node-apn)will gives a better understanding of this topic.

## Creating Certificates

One main step in setting up the notification services is the certificate creation, specific to your app and device. This certificate tells the APN that our server has legal permissions to send and receive notifications of our app. That means the SSL certificate establishes a secure connection with the APNs. The certificate for our is created by us and is specific to our app alone.

Proceed with the below steps to create a certificate:

1. Open the project from Xcode, and select the Capabilities tab from Target.
2. Enable Push Notification switch and wait for automatic configuration to be completed.
3. In the developer center, search for our app in our developer account. Tap Edit.
4. Open the Push Notification section on this screen.
5. Open ‘Create Certificate’ in the Development SSL Certificate tab
6. Follow the procedure in the upcoming steps on the screen to create a certificate. The certificate will be ready for download once created successfully.
7. Download the certificate aps\_development.cer.
8. Select the certificate and private key from the list and export a p12 file. Type in the password and note to remember the newly created password as it will be needed by Apple to send push notifications.

## Obtaining device token

In the above section, we saw the general code to fetch device tokens. Let us consider a scenario-specific code that we can further use for Node.js script creation.

Our sample app is titled SimplRTApp. We need to identify the device tokens to push notifications from the sample app. So, to get the device token, add the following methods on our _AppDelegate.swift_.

![SimplRTApp](https://lh6.googleusercontent.com/tygXGn37MrpeJzTTUBz5scstyVz7XqSPq6-kSKHnzZAg3h9zCqZAikLBDN8KH-eoIleE0gNSdcyZjU1Wa0lKkEv7_XES2c1bAzHwrjBHXZ1Mjk8pTkvC0sbzGmgbzTKnKA1tQv0=s0)

![SimplRTApp](https://lh5.googleusercontent.com/cVkmf9gADkhUwFxcaqFI4pRsYyIuuKTJ8Y7qYQOs9HSrQFzvqrofg2-a_tuZtRq6YPyheG9jPiy7HxQ-_dwxgrtl-1qeatS2SJ1gUnXrNhB0ZKkJ0Bv1WEfpbuHlDeIoTwC4UPU=s0)

View the raw code for the below snippets in the [github library](https://gist.githubusercontent.com/fedejordan/9eda97e5d7b895cdb239ada430f13cab/raw/60382f53919d5293a2870b7f05b792d997e708f2/AppDelegate.swift).

Also, check the [final app code for SimpleRTApp](https://github.com/fedejordan/SimpleRTApp)for further details.

## The Node.js Script Creation

We now have a p12 file to establish a secure connection with the APNs and a device token to send push notifications to this device from our SimpleRTApp. All we need now is to create our program on Node.js and test the push notifications.

To create the Node.js script:

1. Open the terminal app.
2. Need to install the module that handles APN connections. For that, type npm install apn.&nbsp;
3. Copy or save the p12 file to the folder same as that of our Node.js script.
4. Create the below [script](https://gist.githubusercontent.com/fedejordan/89cb4fd33a57d18441469748255b1ec6/raw/5972273eae18a920271a4d777f0daefd9841cbcf/send_push.js)(available from Github).

![Node.js script](https://lh4.googleusercontent.com/QxUH4Xqht-Whh_RDFP_LFJIm6oZE4Oykl7M4998VnupUmFvKrzmj3UMUfQXdAUHv4-g3Ks8ysPLqG6lRgGXvgfmxV-oY5Cjo5zAKOSxgxC-cOazf_ES8rWr5VZ0lLmz3bamdMcQ=s0)

In the script, the \<device-token\> and \<p12-password\> are replaced by the values specific to our app. The above script does the following to set up a real-time push notification when triggered.

- Establish the connection
- Instate the _provider_ object
- Create _Notification_ and send with the _send()_ method
- Finish execution when there is a response for either success or error scenario

With the above script, the push notification setup is complete. Now is the time to test the script. For testing, type node send\_push.js in the terminal and wait for the notification to arrive in the mentioned Apple device.

[Complete script for the push notification](https://github.com/fedejordan/SimpleRTAppAPI) service in check in the GitHub and is available for your reference.&nbsp;

It is a good practice to include a custom action with the notifications. It allows the user to communicate quickly with a proper preset response. Examples for custom actions include the ‘Reply’ or ‘Mark as read’ button in a message notification, ‘Install’ or ‘Snooze’ options in an OS update notification, etc. in our case, one easy and simple custom action would be ‘Retweet’.

Simple edits on the Node.js code shared above will enable these custom actions. Let’s see how to proceed.

While setting the notification object, include below:

![Ios notification object](https://lh5.googleusercontent.com/1_BcdX8WAm3OoJPTmZl701u0ZM-ALoXAamdvl-rpC4iaRkxzbL8NK9Y8A8qT8go3UHTqGiFx0yt1Au6km6LLuL4KlEVyToo-zHJ61sasmn4RBQjw8M5IL0ts3MNTd-DDC9Wbr78=s0)

Also, to let the iOS app know it is an allowed action with the below code:

![IoS notification object](https://lh5.googleusercontent.com/0_72kEE7PHcs2XcmHll7wuzZNgXiZMnKLvSLs9gIA955xn3PxW21cGyR7T3he5MRq1TA-mz-XkZ6swWI3JY_W4fAdbS1uhIVVmuiwrUtoFjeLu4irBwEGGjt3E8l3SAPDMwY96A=s0)

Thus, for our _AppDelegate.swift_, the script would be as follows:

![AppDelegate.swift notification object](https://lh6.googleusercontent.com/Qkie7ZVQ56xynL5k-WByEWoy0OaMuuGOGUsQhERdpOl4MpAmytjB4yHd_xNiKq4jnqNHfuQVRkIJw-GTmHvpLSJbLMRBCj7dR5WP_BKQIpPKCZKbwQvDGLTI9R8ZpWLTylQ5Be0=s0)

![AppDelegate.swift notification object](https://lh5.googleusercontent.com/eZoS38d_5sOnoNo_Btfcj1AWOf17TZfpAg2qqxvcpqDkbuGERVgUUXlv0EXOIZW4afbN5Nisp5CSSH7syylx13Omzu_dfQUmr432z9UhvAkXSqk47wtHdVMEkkofrLxhwnUJ1HQ=s0)

![](https://lh4.googleusercontent.com/pxxXQS5gKsQMYsDf_zC5fY_BYX1FsINT_r-WA8gsR_3VEEZqI-rSK8kg-QBWA7U13vG-7uDSnGXll7Ik46TdAXd-L9Aihc2_qeNz1zwfh-so3jO0TIl59WI_uZAGy1A6n7il9e8=s0)

### Conclusion

As we come to the end of this blog, we have discussed all the below points in detail&nbsp;

- The remote notifications
- APNs
- Certificate creation
- Fetching Device tokens
- Node.js code for delivering push notification