IOS - Rich push duplication after being handled by clicking on UNNotificationAction - ios

After the rich push is handled in the background (user clicked on an UNNotificationAction without opening the app - no foreground)), then when you enter the app, there is a duplicate push event resulting in "didReceiveRemoteNotification" execution.
My question is:
Why when I handle the rich push in:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
and call competionHandler(), same push is being received in:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void)
?
Push setup:
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if granted {
print("UNUserNotificationCenter auth granted")
Utils.performTaskOnMain {
application.registerForRemoteNotifications()
}
} else {
print("UNUserNotificationCenter auth error = \(error?.localizedDescription ?? "")")
}
Push handler
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void)
{
print("AppDelegate didReceiveRemoteNotification, with info:\(userInfo)")
handleNotificationUserInfo(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
UserNotificationsManager.shared.handleActionIdentifierForReceivedNotification(response)
completionHandler()
}
Push notification payload:
info:[AnyHashable("content-available"): 1, AnyHashable("messageInfo"): {"push_type":"XXXX","category":"videoCategory","mediaUrl":"https://XXXX.png","threadId":"24274","alertTitle":null,"initiator":"XXXXX XXXX.mp3","alertBody":null,"mutableContent":true}, AnyHashable("media-url"): https://XXXXX.png, AnyHashable("aps"): {
alert = {
body = "XXXXX";
};
badge = 56;
category = "XXX.videoCategory";
"content-available" = 1;
"mutable-content" = 1;
sound = "XXXX.mp3";
}]

The "duplicate" push that is being delivered to your app is a silent push notification. Your push notification contains the content-available key in addition to the alert dictionary.
The alert dictionary causes a user-visible notification to be delivered.
The content-available key causes it to be delivered again as a silent push notification, which is not visible to the user.
This is an unsupported configuration. Remove the content-available key and only the user visible push notification will be delivered. If you are actively using silent push send it as a separate push with only the content-available, category and your custom keys.

Related

Swift & FCM : How to get push notification data when switching from Background to Foreground?

I'm configuring push notifications in Swift. So far I have 3 scenarios.
1 - App In Foreground
In the foreground, I think I did everything correct cus I did receive the push notification data.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
print("userNotificationCenter willPresent")
let content = notification.request.content
UIApplication.shared.applicationIconBadgeNumber = 0
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
completionHandler([.alert, .sound])
}
2 - User clicks on the Push Notification banner
This is also working fine.
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
print("userNotificationCenter didReceive")
defer {
completionHandler()
}
guard response.actionIdentifier == UNNotificationDefaultActionIdentifier else {
return
}
let content = response.notification.request.content
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
}
3 - App in background, then the user gets into the app
In this scenario, the push notification arrives at the user's phone. But, instead of clicking on the push notification itself, they get into the app. And I can't fetch any info from the push notification
Could anyone help on how to configure the 3rd scenario? Thank you.
you need to consider applicationState
UIApplication.State
//AppDelegate
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
switch UIApplication.shared.applicationState {
case .active:
print("Received push message from APNs on Foreground")
case .background:
print("Received push message from APNs on Background")
case .inactive:
print("Received push message from APNs back to Foreground")
}
}
When the app is background to foreground, UIApplication.State is inactive
inactive is 'The app is running in the foreground but is not receiving events.'
thus I think the best way to do the behavior you want is to write it yourself.
for example,
//AppDelegate
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
switch UIApplication.shared.applicationState {
case .active:
print("Received push message from APNs on Foreground")
case .background:
print("Received push message from APNs on Background")
case .inactive:
print("Received push message from APNs back to Foreground")
guard let nav = window?.rootViewController as? UINavigationController,
let currentVC = nav.viewControllers.last else {return}
if currentVC is 'youWantViewController' { //if you want ViewController, use notification post
let name = Notification.Name(rawValue: K.Event.pushRequest)
NotificationCenter.default.post(name: name, object: nil)
} else { //move to you want ViewController
let vc = 'yourViewController'()
root.navigationController?.pushViewController(vc, animated: true)
}
}
completionHandler(.newData)
}
I hope it will be of help.

Why userNotificationCenter didReceive is not fired?

This is a part of my code. I want to use UNUserNotificationCenter and UNUserNotificationCenterDelegate to handle notification events.
This code catches the notification event when the app is in a foreground state. But "didReceive" is not fired for a background state.
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
UNUserNotificationCenter.current().delegate = self
application.registerForRemoteNotifications()
return true
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void)
{
print("willPresent") /// This works
completionHandler([.alert, .badge, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
print("didReceive") /// This doesn't work
completionHandler()
}
But if I don't use UNUserNotificationCenter.current().delegate = self the delegate method is correctly fired in the background.
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping FetchCompletionHandler) {
print("didReceiveRemoteNotification... \(userInfo)")
}
How can I use "didReceive"? I want to handle the notification in the background.
application(_:didReceiveRemoteNotification:fetchCompletionHandler:) is called when the application receives a silent push notification. Silent push notifications can be delivered in when the application is in the background state, iOS wakes the application to perform background processing invisible to the user.
A silent push notification has the content-available flag set to 1.
Silent push notifications should not include an alert, badge, or sound. Silent push is not meant to be visible to the user, it is only a hint to the application that new remote content is available.
Removing the content-available flag from your push notification payload will cause iOS to handle it as a regular notification. The user notification center delegate methods will be called instead of application(_:didReceiveRemoteNotification:fetchCompletionHandler:) but your application will be unable to do background processing triggered by the notification.
You can validate the content of your push notification payload for problems like this using this tool
This is how I handle push notification in my app. I think you need to implement all of these methods to handle all iOS versions in the foreground and background mode.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound,.alert,.badge], completionHandler: { (granted, error) in
if error == nil {
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
})
}
else {
let notificationTypes: UIUserNotificationType = [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound]
let pushNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil)
application.registerUserNotificationSettings(pushNotificationSettings)
application.registerForRemoteNotifications()
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print(deviceTokenString)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to get token; error: \(error)")
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert,.sound])
//do sth
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
//do sth
}
// for iOS < 10
func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
}
There are methods of UNUserNotificationCenterDelegate:
willPresent: This method gets called when you receive a notification when your app is in the foreground. If the app is in the background then this method will not calls.
didRecieve: This method gets called when a user clicked on the notification.
In case of background state, only 'didRecieve' will be called when user will click on a notification.

Not receiving remote push notifications on iOS

I'm currently rewriting my app from Objective-C to Swift and working on notifications. For some reason Swift version of the app is not receiving any remote push notifications while Objective-C version does.
Here's the code I'm using to register for notifications in AppDelegate:
UNUserNotificationCenter.current().delegate = self
let options: UNAuthorizationOptions = [.badge, .alert, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: options, completionHandler: { granted, error in
print("access granted: \(granted)")
})
application.registerForRemoteNotifications()
I assume that the app successfully registers because didRegisterForRemoteNotificationsWithDeviceToken method gets called. But when I try to send the test notification using the token I got from that method, I don't get actual notification on device.
Also none of these methods get called:
func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType) {
}
func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (_ options: UNNotificationPresentationOptions) -> Void) {
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
}
func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [AnyHashable : Any], completionHandler: #escaping () -> Void) {
}
What am I doing wrong?
you say that you are not receiving so let's first make sure that those methods you mention before that are not being called are comming from here extension AppDelegate: UNUserNotificationCenterDelegate (By the way when you do implement the didReceive method make sure you call the completionHandler() at the end)
When you do this:
application.registerForRemoteNotifications()
Make sure to run it from the main thread, as it can be called if not specified from the background and that might fail. You can do so by doing
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
I'll assume that you are getting the device token this way or something similar:
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)")
}
Finally implement this method to see if there are any errors while registering the device
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)")
}
Oh by the way (just in case you have missed it) make sure you enabled in your project's target the push notification.
Make sure you have enabled Push notification in your project setting capabilities.
How to enable:
go to target: -> select project -> go to capabilities -> go to Push Notification. enable it there.
Another thing is the certificate. While development you should not Production certificates.

How to Read One signal notification if the App is not running in Swift iOS

Actually I need to read those notification instead of tapping the notification banner.
I have used this code
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {}
But this function only gets called when the app is in foreground or the notification banner gets tapped by the user.
I need bunch of code to read the code in Background.
I am using OneSignal Push Notification service.
You can able get the notification responce before notification banner shows. no need tap on notification banner.
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.sound, .alert, .badge])
UIApplication.shared.applicationIconBadgeNumber = 0
alertRemoteNotification(notification.request.content.userInfo as NSDictionary
}

Why I did not receive any notification on my iPhone?

Running this on Xcode8.3 with swift 3.1
Below is my code in AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { granted, error in
if granted {
print("OK!")
}
else {
print("No!")
}
})
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print("==== didReceiveRemoteNotification ====")
print(userInfo)
}
I use node-apns to push notification to my app and I can have message from my Debug area in Xcode.
==== didReceiveRemoteNotification ====
[AnyHashable("id"): 123, AnyHashable("aps"): {
alert = "Hello World \U270c";
badge = 3;
}]
But, I did not receive any notification on my iPhone.
Did I missing something?
With iOS 10, you can do the following to see push notifications when the App is in Foreground. You have to implement the below function in AppDelegate. It's a delegate method of UNUserNotificationCenterDelegate.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void)
Follow the below steps:
Import UserNotifications and extend UNUserNotificationCenterDelegate in AppDelegate.
Set up the UNUserNotificationCenter delegate in didFinishLaunchingWithOptions.
let center = UNUserNotificationCenter.current()center.delegate = self
Implement the will present method in AppDelegate and call the completion handler with the options.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert,.badge,.sound])
}
Now if you get a push, you can see the notification alert even if your app is in foreground. More Info in Apple Doc.
if you want to handle notifications, when your app is active, you should do something like this, because the push view won't appear
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
if application.applicationState == .active {
//create custom view or something
} else {
//it was background/off
}
}
you might be also interested in creating new build schema, so your app will wait until it would be launched, so you can debug your app behaviour when receiving push.

Resources