How to Send Push Notifications to the iOS Simulator
As of Xcode 11.4 beta, you can!
Push notifications are one of the most popular ways for developers to keep users engaged in their apps. In iOS applications, push notifications can be incorporated by using the Apple Push Notification service (APNs).
However, it’s not as easy as it sounds since there is a long list of things to do for setting this up. Plus, what’s worse is that we have to use a real device to test if push notifications are working or not since push notifications aren’t supported in Xcode’s iOS Simulator.
But I have some good news for you. Xcode 11.4 beta is out and the best part about this release for me is that we can finally test push notifications in the iOS Simulator!
The release note of Xcode 11.4 beta consists of a section that says:
“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):
We’ll go in-depth about what this means in the latter part of the post. But for now, let’s be happy because the hassle of having to use a real device for testing push notifications is finally gone.
How Do We Do It?
So, now, let’s see how we can use this newly-arrived feature of Xcode 11.4 beta. For this, you obviously need to have Xcode 11.4 beta or higher. I currently have Xcode 11.4 beta.
Now, let’s create a new project. I’ve named it TestPushNotifications and the user interface I chose is Storyboard. You can choose SwiftUI if you want.
Creating a new project
Just to make the app look good (though it won’t help…), I’ve added a UILabel that says “Hello, world!” in View Controller of Main.storyboard.
Now, when we run the app in a simulator, iPhone 11 Pro Max in this case, it looks like this:
This is where the fun begins! Let’s go to the AppDelegate.swift file and add the following line below import UIKit to import Apple’s UserNotifications framework.
import UserNotifications
Now, in the AppDelegate class, let’s create a function, registerForPushNotifications(), that requests permission from the user to allow the app to send push notifications.
Let’s call the function we just created, from the application(_:didFinishLaunchingWithOptions:) method of AppDelegate.
For that, add registerForPushNotifications() above the return true statement. Your AppDelegate.swift file will look something like this:
//
// AppDelegate.swift
// TestPushNotifications
//
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
registerForPushNotifications()
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
func registerForPushNotifications() {
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
print("Permission granted: \(granted)")
}
}
}
When we run the app, we get a dialog asking for permission to allow the app to send push notifications. Tap Allow.
Dialog asking for permission from the user to allow the app to send push notifications
The release note of Xcode 11.4 beta says:
"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):
Now, let’s try what it says. For that, we require a JSON file with a valid Apple Push Notification Service payload.
Apple’s documentation, entitled “Generating a Remote Notification”, gives a clear idea about how we can create such a file. I’m creating a file named notification.apns on my desktop and adding the following content in it:
Here, <device> is to be replaced by the device identifier, com.example.my-app is to be replaced by your project’s bundle identifier, and ExamplePush.apns is to be replaced by the filename of our apns file.
Note that the bundle identifier is not necessary in the command, if you add it with the “Simulator Target Bundle” key in the apns file.
You can retrieve your simulator’s device identifier by following the steps shown in the GIF below:
Finding the device identifier of the simulator we are using (iPhone 11 Pro Max, in this case)
And you can retrieve the bundle identifier of your project by following the steps shown in the GIF below:
Finding the bundle identifier of the project
Before we execute the command, we have to send the app to the background first. That’s how the push notification will be visible.
Note: If you want the push notification to be visible even when the app is on the foreground, you can make AppDelegate conform to UNUserNotificationCenterDelegate and implement its userNotificationCenter(_:willPresent:withCompletionHandler:) method. And make sure that you have included the following line before calling registerForPushNotifications() in application(_:didFinishLaunchingWithOptions:) method:
As soon as it is executed, this is what we can see in the simulator — a push notification:
A push notification in Simulator
That’s how we can run a command to show push notifications in our simulator!
But wait, if you are not quite comfortable with using the terminal, there’s another way. Remember what the release note said?
“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.”
We can simply drag and drop our apns file into the simulator to get a push notification. But for that, we will have to make some modifications in the apns file.
In the notification.apns file that we created previously, let’s add one more key, "Simulator Target Bundle”, which will hold the value of our bundle identifier, which is “np.com.sagunrajlage.TestPushNotifications” in my case.
Money isn’t everything to the success of the most popular JavaScript frameworks. Or is it? Looking at the 2019 State of JavaScript report , something stands out: Money apparently can’t buy everything. Or, at least, not every major front-end and back-end programming framework is sponsored by a big company. Sure, we have Google to thank for Angular , and Facebook gets credit for React , but what about Vue.js ? Or Gatsby? Or Next.js? While these (and other) open source projects do seem to suggest a future without Big Corps shoveling Big Money into open source, the reality is a bit more nuanced. For the developers looking to pay their way through open source, however, reality isn’t nuanced at all. For every Vue.js founder Evan You making $16,000 per month with Patreon contributions , there are thousands of developers struggling to scrape together $16 for the important open source work they’re doing. [ Also on InfoWorld: 15 great alternatives t...
1 min read 🛍️ Start selling on Facebook Making Facebook work for you hasn't always been easy. Sure, experts told us that selling on social media would be the next big thing. Many of us tried. It didn't always work out... until now. Ecommerce on Facebook should be as simple as a click of your mouse. That's why Shopify introduced the Facebook store. Shopify's Facebook store turns you're Facebook for business page into an e-commerce platform. Easily display products, promote them on Facebook, and sell them to all your fans. 👉 What are you waiting, get your Shopify store connected Today! Who We Are? We are agileHorde Technologies , an award-winning Mobile and Web Apps/E-commerce development company based in India, USA, Philippines. We develop apps that help businesses engage customers effectively . If you want to find out more, or are looking to outsource development of a tailored application, please reach us at info@agilehord...
3 min read Brutalism is a special breed of web design, working well for quirky, creative brands and individuals. However, this rule-bending design technique must be employed with care. Read this guide to find out how. Brutalism is one of those trends that seems to come and go in web design. It’s not because there isn’t much value in brutalist design. It’s more that it doesn’t always fit with the style and tone of the times. That’s part of what makes brutalism so intriguing though. When most websites tend to fall in line and adopt the same basic trends from year to year, a website that doesn’t play by the rules can easily steal the spotlight. You just need to know whether that’s the right kind of light you want to shine on the brand. Brutalism can sometimes come off as cold and somber. If it’s not properly executed or not used for the right kind of brand, it can send the wrong signals to website visitors. In this guide to brutalism in web design, we’l...
Comments
Post a Comment