Push Notification using APNS

1.  Introduction

Apple Push Notification service (APNs), which was launched with iOS 3.0 on June 17, 2009, facilitates sending small sized information to mobile devices remotely. Such information is called a notification and can include:

  • Badge
  • Sound
  • Custom title text alerts
  • Payload

However, delivery of the messages to the intended devices is not guaranteed even though the APN server has accepted the messages. One must pay attention to the below constraints while sending a message:

  1. Push notifications are fire and forget, which means, it is not possible to find the status of the message after submitting it to APNs.
    Similarly, time taken to deliver the notification will also vary, while sometimes it happens instantaneously other times it may take up to 30 minutes or more.
  2. Prior to iOS 8, maximum payload for each notification was 256 bytes which was changed to 2 KB with the advent of iOS 8. Any notification which doesn’t honor the pay load limit will be rejected by the APNs.

2.  Prerequisite

  • iOS(iPhone/iPad) device

Since emulator doesn’t support push notifications, an iOS device with the latest OS is required.

  • Developer program membership

To create various profiles and certificates, which are used in sending push notifications to all the registered devices.

  • APN Tester Free App

APN Tester Free is a MAC app which is very handy tool to check push notification, which is simple and easy to use.

3.  Push Notification Flow


  1. When the user accesses the app for the first time on the device an alert is displayed seeking the permission for push notifications.
  2. Device gets token, upon user’s confirmation, which is made up of unique HEX numbers. Tokens are used to identity the iOS device while sending notifications.
  3. Copy Device token and upload APNs certificate into APN Tester Free App
  4. APN Tester Free App will push the notification request object to APNs, which includes device token, payload.
  5. APN server will push the notification to the device which has registered device token mentioned in device token column in APN Tester Free App.

When a notification is sent to user’s device an alert is displayed accompanied by sound and can also show badge (count of unread notifications) over the app icon.

Local notifications (sent from device to the same device) are also possible but are beyond the scope of this document.

4.  Certificates, Profiles and developer account

Each iOS app needs a provision profile plus a security certificate. Such provision profile and certificate can be used for single app i.e., they can’t be shared across multiple apps.

Target App ID should be configured for push notifications in the Apple Developer account , as push notifications are not going to work unless the App ID is configured with Push notification service.

Certificate used by the app is driven by the app’s state: in development or already pushed to the store. Production certificate is used when the app is in store otherwise development certificate is used.

Whatever may be the app’s state, it is very important to use proper certificate depending upon the app environment i.e., Production or Development, otherwise push notifications will not work.

5.  Enough of theory, let’s dive in

This Blog considers development certificate only. Follow the below instructions if a development certificate doesn’t exist.

A CSR certificate is needed to generate the developer certificate. Open key chain access – > Certificate Assistant ->Request a Certificate >From a Certificate Authority


Enter a value in the Common Name. User and CA email addresses can be the same. Select Saved to disk option.

Give a name to the CSR file, such as NotifyApp.certSigningRequest and click on Continue button to save the CSR file.


Open key chain access and click on the keys under category. A private key called NotifyApp will be created.


Right click on the NotifyApp and choose the export option to get a file with p12 extension. Please use a strong password while saving the p12 file and keep it at a safe location and we move onto developer account:

Select Certificates, Identifiers & Profiles.


Select Identifiers menu.


Select App IDs and click on the app’s name if it is already present else click on + button and follow the instructions.


Scroll down till you see the Push Notifications option which will be in disabled state if it was not selected during the App Id creation.


Click on Edit option if its Disabled. Click on the Create Certificate and upload the NotifyApp.certSigningRequest certificate.

Scroll down to Push Notification section and click on the check box.


Push notifications will be enabled and are ready for configuration, upon selecting the Push Notifications check box. Next step is to click on “Create Certificate…” under Development SSL Certificate.


Read the instruction and click on the Continue button.


Click on Choose File button and select the CSR file which was created with the help of Keychain.


Click on Continue button.


Click on download button, a certificate with .cer extension file will download. Click on Done button.


Certificate can be downloaded and saved to disk from this screen also.


Push notifications configuration is complete.


The certificate downloaded will have name as “aps_development.cer “, which can be changed to suit individual needs. However, default name of the certificate will meet most of the needs.

For future reference keep all the files generates so far in a folder:

  • CSR File
  • Private Key file with .p12 extension
  • Downloaded certificate file with .csr extension

In this tutorial, file .cer extension is used. If any other server such as Parse is used, then files with .p12 extension are used instead.

Note: Apple has two servers, one for testing and one for production. We need to insert sandbox inside the gateway URL.


For creating the provision profile for new project, please go through the link:

After creating the provision profile double click on it to add it to XCODE.

6.  Create a new app for push notification.

Create a project with name NotifyApp and give it a bundle id: com.example.NotifyApp

6.1  Device Token

Open AppDelegate.m file and replace didFinishLaunchingWithOptions with the following:

(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Register the device to use for notification.
if([[[UIDevice currentDevice]systemVersion]floatValue]<10.0)
     [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound |    UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
     [[UIApplication sharedApplication] registerForRemoteNotifications];
     UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
     center.delegate = self;
     [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error)
        if( !error )
           [[UIApplication sharedApplication] registerForRemoteNotifications];
           NSLog( @"Push registration success." );
           NSLog( @"Push registration FAILED" );
           NSLog( @"ERROR: %@ - %@", error.localizedFailureReason, error.localizedDescription );
           NSLog( @"SUGGESTIONS: %@ - %@", error.localizedRecoveryOptions, error.localizedRecoverySuggestion );
return YES;

NOTE: For iOS 10, you need to import UserNotifications framework

#import <UserNotifications/UserNotifications.h> and add its UNUserNotificationCenterDelegate  in Appdelegate.h file

Run the project to check if a pop-up seeking permission for push notification is displayed. Press OK to allow the notification.

Add two more methods to get the response and device status from the server.

-(void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
     NSLog(@"Device token received is: %@", deviceToken);

Device tokens are 64 hexadecimal characters in length and 32 bytes in size. Sample Device Token: 

-(void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
NSLog(@"Failed on receiving the token error: %@", error);

Below mentioned delegate method will fire, whenever Push notification is dispatched from the server.

-(void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
    NSLog(@" UserInfo: %@", userInfo );

7.  Download APN Tester Free app

APN Tester Free app is very handy tool to check push notification, which is Its simple and easy to use.  Here is the link



Just include the device token, Payload (push notification data in JSON format), and apn_certificate.cer file (details on how to create it are explained in earlier sections).

Finally, select the Development option and hit Push button to send out the push notification.


8.  Things to remember

  1. Same CSR can be used to generate a new certificate when an existing certificate has expired. New CSR will create a new private key whereas existing CSR will reuse the private key.
  2. Firewall should be configured to allow outgoing connections on Port # 2195, otherwise communication with APNs will fail.

9.  References

AppDistribution Guide

About the Author:

I am Md Aslam Ansari, an iOS developer at Osmosys Software Solutions. I love developing mobile apps and web pages. I have passion for biryani, pizza and movies. In free time I make pencil sketches and do exercise. Did I mention I love biryani.

Are you interested? follow us and get notified of new posts

One thought on “Push Notification using APNS

Leave A Reply

20 − twelve =