Push Notification In iOS Swift 2

Push Notification In iOS Swift 2

  • What Is iOS Push Notification?
  • Uses For Push Notification
  • How iOS Push Notification Work
  • iOS Push Notification App Tutorial
    1. Create Project
    2. Configure App Capabilities
    3. Register App For iOS Push Notification
    4. Creating a Certificate Signing Request (CSR)
    5. Configure Provision Profile of iOS Push Notification
    6. Export Certificate
    7. Convert Certificate
    8. Test Connection
    9. Create PHP Script

What Is iOS Push Notification?

Push notifications are simple messages from apps installed on a device that wake up the handset and alert the user with a message displayed on the home or lock screen. Push notifications are widely used on all mobile devices as a way to inform or update the user. They are generally accepted as a great way to bring app users back to your app.

Uses For Push Notification

There are many uses for push notifications across all app types and they are being adopted by more and more brands as a means of increasing app engagement and user retention.

Here some example:

engagement 20% off today only, purchase before 12pm and you’ll get free next day delivery.

  Description Notification
GAMING Notify users of changes in league tables to encourage them to return to the app. Appeal to their competitive nature. Hi Jon , your top score has been beaten, log on now to compete.
RETAIL Drive users back to your retail app with attention grabbing offers and promotions, with a short snappy call to action to encourage “there and then?
ENTERTAINMENT Update your users on what’s happening now, what do they really want to know that will make their lives easier? Your Radio2 podcast is now ready to download.
PUBLISHING Don’t forget that everyone forgets, if your user is paying for a service from you, they’ll appreciate your help in remembering it! The new issue of Vogue is ready to read, get it now for your free scarf
For large enterprises with their own apps, Push Notifications can be really helpful to produce urgent and important updates for staff for disaster recovery or event issues. Server farm A is now offline, reboot will occur at 1800hrs. Email will not be available off site until then.

How iOS Push Notification Work

ios push notification

ios push notification - provider copy

  1. The device sends a request to Apple Push Notification service (APNs) for registration.
  2. APNs return device token.
  3. The device gives this device token to an app.
  4. The app sends this device token to its provider (their server).
  5. The provider sends notification text with device token to APNs.
  6. APNs send this notification to the device.

iOS Push Notification App Tutorial

Step 1 – Create Project

Create new Xcode project and select “Single View Application” template. Enter your project name as ios push notification app tutorial or something and set swift as a programming language.

Step 2 – Configure App Capabilities

Go to project setting and find Capabilities tab. Here you can see the list of Capabilities like iCloud,Game Center etc. Find the Push Notification and turn on.

Configure App

Step 3 – Register App For iOS Push Notification

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert, categories: nil))
return true

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {


func application(application: UIApplication, didReceiveRemoteNotificationuserInfo: [NSObject : AnyObject]) {

Add the above code in your AppDelegate.swift file and run your app.

If any error then iOS call ‘didFailToRegisterForRemoteNotificationsWithError‘  method that define in AppDelegate.swift file. Here you can get error, so you can understand that what is the problem and after fix that run app again.

if your device register successfully then iOS call ‘didRegisterForRemoteNotificationsWithDeviceToken‘ method that define in AppDelegate.swift file. Here you can get device token.

When you see that device token it’s look like this :

<90bc11f1 c64d7a4e 2611ab79 dbc8becd 6bf1d3b4 d2b44cd6 53a02cde d88842ac>

Copy device token and paste in text file and Remove brackets and space. After removing that brackets and spaces device token look like this :


Step 4 – Creating a Certificate Signing Request (CSR)

In the Applications folder on your Mac, open the Utilities folder and launch Keychain Access. OR press + Space type Keychain Access.

Within the Keychain Access drop down menu, select Keychain Access > Certificate Assistant > Request a Certificate from a Certificate Authority.

  • In the Certificate Information window, enter the following information:
    • In the User Email Address field, enter your email address.
    • In the Common Name field, create a name for your private key (e.g., push-notification).
    • The CA Email Address field should be left empty.
    • In the “Request is” group, select the “Saved to disk” option.

Step 5 – Configure Provision Profile of iOS Push Notification

Now go to Member Center. Find Certificates, Identifiers & Profiles > Provisioning Profiles > Development

Find your provision profile. When Xcode create provision profile, in status you see something like this “Active (Managed by Xcode)”.

Go to Xcode and open project settings (step 2). Click on General. Here you can see your Bundle Identifier. Now check that which provision profile match this bundle identifier.

After you conform provision profile,  check the Push Notification line you may find the text like this ‘Configurable’.

Configure provision profile

Click on Edit.

Enable push notification

Click on Create Certificate in Development SSL Certificate section.

When asking CSR file to upload, upload file that we create in Step 4 and click on generate button. When your certificate is ready download it.

Step 5 – Export Certificate

Now open that certificate.

Export certificate

Select My Certificates in “Category” and select Login in “Keychains”. Now right click on your certificate and select export.

certificate export

You Need two files. First is .CER file and the second one is .p12 file.

In export, the window goes to file format and select .cer format and save to desktop. for convenience  use this name  “PushCertificate.cer”

Now again right click on your certificate and click export. This select  .p12 file format set the file name to “PushKey” and save to desktop.

certificate export

When you click on the save button keychain asking you to password for that file. Set password and hit the ok button.

Again keychain asking you to password for export at this time enter your account password.

Step 6 – Convert Certificate

For our PHP script to be able to communicate with APNS to send ios push notification, we need to feed it the SSL certificate that we generated earlier in the iOS development portal. This is why we extracted the .cer certification and the .p12 private key files, which we now need to feed to our PHP script. The way this works is that we will use the openssl in Terminal to combine the certificate and the .p12 private key into a PEM file.

Now Copy both file “PushCertificate.cer” and “PushKey.p12” and past to desktop. Open Terminal OR  press + Space type “Terminal”

Type the following command :

Command 1 :

openssl x509 -in PushCertificate.cer -inform der -out PushCertificate.pem

PushCertificate.pem file is created on your desktop.

Command 2 :

openssl pkcs12 -nocerts -in PushKey.p12 -out PushKey.pem

PushKey.pem file is created on your desktop.

You will be asked to enter the import password.Just Press Enter. After that, you see this message “MAC verified OK”.

After the importing password is checked and verified, you will be asked by OpenSSL to specify a passphrase for the resulting PEM file. The password needs to be at least 4 characters. Go ahead with that and make sure you remember this password for later use.

Now you have two PEM files on your desktop: PushCertificate.pem and Push Key.pem. You need to combine them into a single PEM file, the format recognized by PHP. Use the following command to accomplish this task:

Command 3 :

cat PushCertificate.pem PushKey.pem > PushCertificateAndKey.pem

PushCertificateAndKey.pem file is created on your desktop.

Make sure that you are in desktop directory in your terminal when typing above commands.

Step 7 – Test Connection

Now let’s test if we can connect to the sandbox(testversion,for development purposes) APNS server using the generated .pem files. Run the following command in Terminal:

Command 4 :

openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert PushCertificate.pem -key PushKey.pem

If everything goes well, you will be asked to enter the passphrase for your private key file. Remember it? (Step 6) OK, then, enter that here. If your connection is successful, you will see OpenSSL waiting for some input characters before closing the connection. Type in something random and press the Enter key. The connection is then closed. This means that your connection to the APNS server is successful with the given certificate and private key.

Step 8 – Create PHP Script

Final step for iOS push notification, it is now time to set up a simple PHP script to push a simple notification to our device.

But before we move forward any further, we need to get our device’s push notification token in a format that can be understood by PHP. iOS encapsulates the push notification token in an instance of NSData, but PHP has no notion of what that means. We need to convert that token into a string that we can use in our PHP script.We already do this in Step 3.

Download PHP Script File

[sociallocker] push-notification.zip [/sociallocker]

Go through this script, even if you are not a PHP programmer, and read the comments. Ensure that you replace the values in the PHP script with the correct values for you. For instance, the device token used here is for my personal device. Use the device token that you retrieved for your own device earlier in Step 3. The passphrases and the .pem file locations may be different for you. What I did is to make sure things are easier is to place my PHP script in the same folder where I placed my private key and certificate .pem file (PushCertificateAndKey.pem) so that I can access the .pem file using a simple filename.

If you did everything right, you should now be able to Run your PHP script in a web browser and see the notifications on your device. The script sends the notification to the APNS server, which delivers it to the device.

Make sure that you have Apple device that running on iOS 8 or later . Push notification not work on simulator.

You have to Developer account that enroll Apple Developer Program.

I hope you will find this post very useful regarding iOS Push Notification. Let me know if you have any question regarding  iOS Push Notification in a comment. I will reply to you ASAP.

Have you got a cool idea about iPhone App Development? Contact us Now to get a free consultation on your idea. Alphanso Tech is rated as one of the best iPhone App Development Company in India.

[Selected_Post_In_Sidebar note=”read Description”]1650,2621,7717,2975[/Selected_Post_In_Sidebar]

Post by Milan Sanathara

I am iOS Application Developer with an aspiration of learning new technology and creating a bright future in Information Technology.

16 Responses to Push Notification In iOS Swift 2

  1. essa

    After i make all thing and run the php script i see this message

    Failed to connect to the APNS server. Error = Connection timed out

    please help

  2. Jim

    I’ve been browsing on-line more than 3 hours today, yet I
    never discovered any attention-grabbing article like yours.

    It’s lovely price enough for me. In my view, if all site owners and bloggers made good content material as you did, the internet can be much more useful
    than ever before.

  3. Michel

    Excellent article, took me some time to set up it but it works like a charm!
    How does the development setup change from when your app is in the appstore?
    In other words, what needs to change for this to work once my app is in the appstore?

    Kind regards,


  4. Michel

    Hi Milan,

    What do you mean with step 2, change apns server?
    I’ve build my own backend with can sent to multiple tokens now, can’t I use that?

    Best regards,

    • We are using the sandbox version of the APNS for development, for production environments change this to ssl://gateway.push.apple.com:2195. Remember for your each app (submitted to app store), You need to separate certificate. When you use your backend, just remember that you send right data to your backend and your backend find its certificate file.

  5. kurt warson

    After all the steps , and when I run the php script I got “successfully send the message” however I don’t see a message appear on my iphone, anyone an explanation for this?

    Thanks in advance

  6. Harsh


    Great tutorial! In my app, I dont have backend server I would like to keep it that way. As I can see push notification requires backend to deal with this, I can save device ID’s in CloudKit to send notifications to specific device, but I dont understand how I can handle this all from app, specially php script, if I wanted to change the target device ID in script.


  7. Pingback: Native, Hybrid or Web Application; What your business needs? - AlphansoTech

  8. Deepak

    Hi, MILAN
    This tutorial is very much helpful and it works for me.
    I have just one question how I can send push message to multiple device token .

    Thanks ,

  9. Pingback: Top 7 Business Problems Mobile App Development Can Solve

Leave a Reply

Your email address will not be published. Required fields are marked *