You are currently viewing Simulating Push Notifications in iOS Simulator

Simulating Push Notifications in iOS Simulator

Dear fellow iOS developers, the wait is finally over! We are now able to simulate push notification in iOS simulator using the latest Xcode beta release (11.4-beta).

Without further ado, let’s see how this can be done.


The Steps

In order to be able to simulate a push notification in iOS simulator, there are a few steps that need to be taken.

  1. Download and install Xcode 11.4-beta and above.
  2. Create a sample app that requests for permission to receive push notifications.
  3. Run the sample app and grant it permission.
  4. Put the sample app into the background.
  5. Create an Apple Push Notification Service (APNS) payload file.
  6. Drag and drop the payload file onto the target simulator.

Now let’s go through these steps in detail one by one.

1. Download and install Xcode 11.4-beta and above

By the time this article is being published, Xcode 11.4 is still under beta release. Thus, you can download it here.

If you are reading this after Xcode 11.4 officially released, just go ahead and download it in the Mac App Store.

Do note that the Xcode beta release is bundled within its own sandbox, therefore you do not need to worry that the beta installation will overwrite your current Xcode version.

2. Create a sample app that request for permission to receive push notifications

Fire up Xcode and create a new “Single View App” project.

Go ahead and open the AppDelegate.swift file and import the UserNotifications framework.

import UserNotifications

Next, add the following block of code into the application(_:didFinishLaunchingWithOptions:) method to request permission to receive push notifications.

UNUserNotificationCenter.current()
    .requestAuthorization(options: [.alert, .sound]) {(granted, error) in
        // Make sure permission to receive push notifications is granted
        print("Permission is granted: \(granted)")
}

Here’s how your AppDelegate.swift should look like.

Request for permission to receive push notification in iOS
Request for permission to receive push notification

3. Run the sample app and grant it permission

Now press ⌘R to build and run the sample app, you should be prompted to grant permission to receive push notifications.

Push notification permission alert
Prompted to grant permission

Go ahead and tap “Allow” to grant the permission.

4. Put the sample app into background

You can press Shift + ⌘ + H to bring your app to the background in a simulator.

Note that this step is very important if you want to see a push notification banner being shown at the top of the screen.

We will get into showing push notifications when app in foreground later.

5. Create an Apple Push Notification Service (APNS) payload file

The APNS payload file is a JSON file that contains information about the push notification. You can find out more by referring to this Apple’s documentation.

Before creating the payload file, we need to grab the sample app’s bundle ID from Xcode.

Get bundle ID from Xcode
Get bundle ID from Xcode

After getting the sample app’s bundle ID, we can proceed to create the payload file. For demonstration purposes, we will use a payload file with the following content.

Note that the value of “Simulator Target Bundle” will be the bundle ID you just retrieved from Xcode.

{
  "aps": {
    "alert": {
      "title": "Swift Senpai",
      "body": "🥳 Woohoo! Push notification in simulator! 🎉",
      "sound": "default"
    },
    "badge": 10
  },
  "Simulator Target Bundle": "com.LeeKahSeng.SwiftSenpai-Push-Notification-Demo"
}

At the moment, just save the APNS payload file on your desktop.

6. Drag and drop the payload file onto the target simulator

Now, drag the payload file you just saved and drop it onto the simulator to see everything in action. (In order for this to work, the sample app must be in background)

simulate push notification in iOS simulator
Drag and drop payload file to show push notification

Congratulations, you have just received your first push notification using a payload file. 🎉

But wait! Besides drag and drop, you can also trigger a push notification in simulator by using Terminal. Let’s have a look at how this can be done.


Simulate Push Notifications Using Terminal

In order to simulate push notifications using Terminal, you must first get the iOS simulator identifier.

In Xcode, press Shift + ⌘ + 2 to open the “Devices and Simulators” window. You can follow the instructions in the image below to get the simulator identifier.

Find iOS simulator identifier in Xcode
Getting simulator identifier

Once you get the simulator identifier, you can trigger a push notification using following command:

xcrun simctl push <simulator-identifier> <path-to-payload-file>

For my case, this is the command I will use.

xcrun simctl push 27A23727-45A9-4C12-BE29-8C0E6D1E5360 payload.apns
simulate push notification in iOS simulator using Terminal
Simulate push notifications using Terminal

Note:

“xcrun simctl push <simulator-identifier> <path-to-payload-file>” may throw “xcrun: error: unable to find utility “simctl”, not a developer tool or in PATH ” unless you have enabled Command Line Tools. To enable command line tools, go to Xcode > Preferences > Locations > Command Line Tools, and then select the desired Xcode version. On top of that, this command needs to be run within the folder where payload.apns located.

Pointed out by Medium reader T.

Simulate Push Notifications When App In Foreground

Lastly, let’s look at how you can simulate a push notification when your app is in foreground.

Head back to Xcode and open AppDelegate.swift.

First, conform the AppDelegate class to the UNUserNotificationCenterDelegate delegate. Next, implement the userNotificationCenter(_:willPresent:withCompletionHandler:) delegate method.

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    print("Push notification received in foreground.")
    completionHandler([.alert, .sound, .badge])
}

Last but not least, set the AppDelegate as delegate of UNUserNotificationCenter. Add the following line of code into the application(_:didFinishLaunchingWithOptions:) method.

UNUserNotificationCenter.current().delegate = self

At the end, your AppDelegate.swift should look like this.

Receive push notification when app in foreground
Changes on AppDelegate.swift

Now, bring your app to foreground and drop the payload file onto the simulator, you should see the push notification banner magically appear at the top of the screen. 🎊

simulate push notification in iOS simulator
Simulate Push Notifications When App In Foreground

Known Issues

Up until the publish date of this article, I found out that the badge number is not showing up. On top of that, no sound is played when the push notification is triggered.

At this moment, Xcode 11.4 is still under beta release. I am sure Apple will fix these issues before the official release.


Further Readings


I am super excited about this new feature in Xcode. How about you? Share this article to your friend if you feel the same too!

Follow me on Twitter for more articles related to iOS development.

Thanks for reading! 👨🏼‍💻


👋🏻 Hey!

While you’re still here, why not check out some of my favorite Mac tools on Setapp? They will definitely help improve your day-to-day productivity. Additionally, doing so will also help support my work.

  • Bartender: Superpower your menu bar and take full control over your menu bar items.
  • CleanShot X: The best screen capture app I’ve ever used.
  • PixelSnap: Measure on-screen elements with ease and precision.
  • iStat Menus: Track CPU, GPU, sensors, and more, all in one convenient tool.