• An iOS device: Push notifications don’t work in a simulator, so you’ll need an actual device.

• An Apple Developer Program membership: To send push notifications, you need a push notification certificate for your App ID, which requires a program membership.

• PushNotifications: You’ll use this utility app to send notifications to a test device. To install it, follow the instructions under How to install. To send and receive push notifications, you must perform three main tasks:

• Configure your app and register it with the Apple Push Notification service (APNs).

• Send a push notification from a server to specific devices via APNs.

• Use callbacks in the app to receive and handle push notifications.

Here is what you can do with APNs these days:

1. Display a message

2. Play a sound

3. Set a badge icon on your app

4. Provide actions the user can act upon with or without opening the app

5. Show an image or other type of media

6. Be silent but ask the app to perform some action in the background

Besides all that, there are two kinds of remote notifications: Sandboxed that can be used in the development stage so it’s possible to test notifications, and Live that are meant to be used only in production stage. If you manage to successfully receive sandboxed notifications in your app and at the same time you have taken all the actions that were shortly mentioned above properly, then you can be sure that live push notifications will work too. Needless to say that Apple provides test servers for sending sandboxed notifications, and it’s not the production APNs for that purpose.

So, lets start to configure our project.

The Certificate Signing Request

What you need is the Development SSL Certificate(clarification regarding development vs. productions certificates provided at the end of the article), click on the Create Certificate Button, and follow the instructions to create a CSR File. In short, hold CMD + Space to start the spotlight search on your Mac, write Keychain Access, and press enter to launch the Keychain Access App:

Properly fill in the Certificate Information and make sure you save the .certSigningRequest file at an easy-to-find place because then you need to upload it later.

Click Continue and optionally choose a folder and a name for the CSR file right before you save it. Once you see a message saying that your certificate request has been created on disk, click Done and you’re… done. The certificate we just requested for and saved to disk will be used to sign other certificates in the Apple Developer website.

APNS Configuration and initial step-by-step implementation

Step 1, project set-up: Like anything else you are probably learning these days about iOS apps, it all starts with creating a project. That is right, mine is named Unicorner. The idea is simple — when a fellow unicorner user sees a unicorn and takes a picture of it, every user will receive that picture in a notification.

Step 2, enabling APNs: In Xcode, go to your Targets, under your app’s name, select Capabilities and find Push Notifications in the list, switch to ON:

Step 3, get APNs certificate: Go to your Apple Dev Member Center Account and log in. Click Certificates, IDs & Profiles -> Identifiers -> App IDs where you should see all your app identifiers, select the one you are creating the notifications for. You will see a big list of Application Services available — Push Notifications should be marked as configurable:

Next, find Edit button at the bottom, click it and find Push Notifications in that list again:

It’s about time now to make use of the Certificate Signing Request file we created through the Keychain Access app a couple of parts ago. So, let’s keep going with that process, and in the first step of the guide just click to the Continue button. Here you get just some instructions on how to generate the CSR, in case you haven’t done so already.

Next, click to the Choose File… button so you can search for the CSR file that you generated in the first step. If you hadn’t changed the default file name, then you’re looking for a file titled CertificateSigningRequest.certSigningRequest or Whatever you had stored file name.

Do that. Then you will get this screen:

Download the generated Certificate, double-click the .cer file and find it it installed in your Keychain Access:

Once you locate the new certificate in the Keychain, right click on it, and then click to the Export “…” option.

Make sure that the .p12 file format is selected before you click to the Save button.

Last before coding, You can skip setting a password simply by clicking to the OK button in the next window. If you set one, make sure to remember it or write it somewhere, because the file becomes unusable if you forget it.

Note that in this tutorial we are not going to use the file you just exported. You are going to need it, however, in case you want to test push notifications from a server like Parse, where you have to provide the .p12 file before even sending your first notification. So for now just keep that file along with the rest. At this point it’s important to realise that knowing how to generate a .p12 file for development mode enables you to do the same for the production stage as well.

This step was a long one but worth it. Follow these steps again Certificates, IDs & Profiles -> Identifiers -> App IDs and you should see that Push Notifications are now enabled for Development:

Do Code

Go back to the project and open the AppDelegate.swift file. This is where we are going to ask the user for a permission to receive notifications from us before we try sending some.

import UserNotifications

func registerForPushNotifications() {

UNUserNotificationCenter.current().delegate = self

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (

granted, error) in

print("Permission granted: (granted)")

// 1. Check if permission granted

guard granted else { return }

// 2. Attempt registration for remote notifications on the main thread

DispatchQueue.main.async {

UIApplication.shared.registerForRemoteNotifications()

}

}

}

we access the instance of the UserNotificationCenter, and then ask it to authorize us to send push notifications to the user in the form of alerts, sounds and badge app numbers. If granted, we call the registerForRemoteNotifications() function of the shared application instance on the main thread. We need to explicitly do it on the main thread or else, we would get the annoying error saying that we are calling the function on a background thread .

Then we call registerForPushNotifications() function at the end of

application(_:didFinishLaunchingWithOptions:) but before the return true statement, like this:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:

[UIApplicationLaunchOptionsKey: Any]?) -> Bool {

registerForPushNotifications()

return true

}

Registering for push notification is important, but it consists of the half programming work we have to do only. The other half regards the implementation of some useful delegate methods that make your app properly respond to received notifications. So let’s see them one by one.

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

// 1. Convert device token to string

let tokenParts = deviceToken.map { data -> String in

return String(format: "%02.2hhx", data)

}

let token = tokenParts.joined()

// 2. Print device token to use for PNs payloads

print("Device Token: (token)")

}

func application(_ application: UIApplication,

didFailToRegisterForRemoteNotificationsWithError error: Error) {

// 1. Print out error if PNs registration not successful

print("Failed to register for remote notifications with error: (error)")

}

The code in the didRegister … function may seem weird at first but all it does is stringify the token for us so we can use it within the Pusher App.

Note: Pusher App is available publically on internet. Download and install it in your system. Now, you are able to test your push notifications.