Send Push Notifications to the iOS Simulator

Nirmal Choudhari
Globant
Published in
2 min readFeb 11, 2020
PUSH NOTIFICATIONS

Yes, that’s true. I always wondered if I can send a Push Notification on iOS simulator instead getting a real device while developing applications.

As we all know push notifications plays very crucial role in user engagement. Hence it becomes more important feature in an application

What you need is Xcode 11.4 beta. The release notes has mentioned about sending push notifications on simulator

Simulator supports simulating remote push notifications, including background content fetch notifications. In Simulator, drag and drop an APNs file onto the target simulator. The file must be a JSON file with a valid Apple Push Notification Service payload, including the “aps” key. It must also contain a top-level “Simulator Target Bundle” with a string value matching the target application‘s bundle identifier.

simctl also supports sending simulated push notifications. If the file contains “Simulator Target Bundle” the bundle identifier is not required, otherwise you must provide it as an argument (8164566):

$ xcrun simctl push <device> com.example.my-app ExamplePush.apns

Implementing Push Notifications

  1. import UserNotifications
  2. Register for push notifications

Add below line in applicationDidFinishLaunching

UNUserNotificationCenter.current().requestAuthorization(options:   [.alert, .sound, .badge]) {(granted, error) in 
print("Permission granted: \(granted)")
}

3. Run the application and keep in background

4. Let’s create a JSON file with payload. Apple documentation on Payload explains more about it. Create payload.apns , add below JSON to it and save.

{
"aps" : {
"alert" : {
"title" : "Push On Simulator",
"body" : "You have sent it on simulator"
},
"badge" : 7
}
}

5. Command Line

Using simctl command to simulate remote notification

xcrun simctl push <device> <bundle-identifier> <path-to-apns-file>

example

xcrun simctl push booted com.nirmal.simpush payload.apns

You can also get the list of devices using xcrun simctl list if you have multiple simulators running

You don’t need to add bundle identifier to the command if your payload contains Simulator Target Bundle . See example below.

{
"aps" : {
"alert" : {
"title" : "Push On Simulator",
"body" : "You have sent it on simulator"
},
"badge" : 7
},
"Simulator Target Bundle" : "com.nirmal.simpush"
}

6. Drag and Drop

You can also drag and drop payload.apns to simulator to see the notification. Make sure the file you are using must have Simulator Target Bundle to work it correctly.

References

--

--