UNNotificationAction with Firebase remote notification is not showing up - ios

I am stuck for few days for trying to add UNNotificationAction buttons for my remote notifications that support iOS 9, 10 and 11. I followed all the steps from multiple tutorials, most of them are using local notification to show the UNNotificationAction which are working so far. However it doesn't work for my remote notification. I am able to send remote notification via Firebase. Please do let me know if some parts of my code are incorrect or missing parts to configure UNNotificationAction buttons.
Those code in my AppDelegate,
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
requestNotificationAuthorization(application: application)
}
return true
}
func requestNotificationAuthorization(application: UIApplication) {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {granted, error in
if (granted)
{
let viewAction = UNNotificationAction(identifier: "viewAction", title: "View", options: [])
let closeAction = UNNotificationAction(identifier: "closeAction", title: "Close", options: [])
// 2
let buttonCategory = UNNotificationCategory(identifier: "buttonCategory", actions: [viewAction, closeAction], intentIdentifiers: [], options: [])
// 3
UNUserNotificationCenter.current().setNotificationCategories([buttonCategory])
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
print("Granted")
}
})
} else {
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: notificationAction() as? Set<UIUserNotificationCategory>)
application.registerUserNotificationSettings(settings)
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
}
func notificationAction() -> NSSet {
let firstAction: UIMutableUserNotificationAction = UIMutableUserNotificationAction()
firstAction.identifier = "First_Action"
firstAction.title = "View"
firstAction.activationMode = .foreground
firstAction.isDestructive = false
firstAction.isAuthenticationRequired = false
let secondAction: UIMutableUserNotificationAction = UIMutableUserNotificationAction()
secondAction.identifier = "Second_Action"
secondAction.title = "Close"
secondAction.activationMode = .background
secondAction.isDestructive = false
secondAction.isAuthenticationRequired = false
//category
let firstCategory : UIMutableUserNotificationCategory = UIMutableUserNotificationCategory()
firstCategory.identifier = "buttonCategory"
let defaultAction = [firstAction,secondAction]
let mininalAction = [firstAction,secondAction]
firstCategory.setActions(defaultAction, for: UIUserNotificationActionContext.default)
firstCategory.setActions(mininalAction, for: UIUserNotificationActionContext.minimal)
//NSSet of category
let categories = NSSet(object: firstCategory)
return categories
}
#available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// iOS10+, called when presenting notification in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert])
}
// iOS10+, called when received response (default open, dismiss or custom action) for a notification
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
if(response.actionIdentifier == "viewAction"){
print("viewing Action")
}
if(response.actionIdentifier == "closeAction"){
print("closing Action")
}
completionHandler()
}
}

There are several steps to making iOS remote notifications via Firebase work, and many of them are not code-related. First make sure that you are able to send/receive a simple text-only notification, without Actions.
Once that's working, then see if you are receiving the built-in actions, UNNotificationDefaultActionIdentifier and UNNotificationDismissActionIdentifier.
If that works, then you should only need the code from your delegate methods and requestNotificationAuthorization method - your notificationAction() method seems unnecessary.

Related

how to access push notification response without tapping on banner or before showing notification?

I'm implemented push notification in my app in this way
//MARK:- Register notifications
func registerForPushNotifications() {
if #available(iOS 10.0, *){
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
if (granted)
{
UIApplication.shared.registerForRemoteNotifications()
}
else{
//Do stuff if unsuccessful...
}
// Enable or disable features based on authorization.
}
}
else
{
//If user is not on iOS 10 use the old methods we've been using
let types: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
let settings: UIUserNotificationSettings = UIUserNotificationSettings( types: types, categories: nil )
UIApplication.shared.registerUserNotificationSettings( settings )
UIApplication.shared.registerForRemoteNotifications()
}
}
//MARK: Push Notifications Delegate Methods
func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) {
var token = ""
for i in 0..<deviceToken.count {
//token += String(format: "%02.2hhx", arguments: [chars[i]])
token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
}
USER_DEFAULTS.setValue(token, forKey: "Device_ID")
USER_DEFAULTS.synchronize()
}
func application( _ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error ) {
print( error.localizedDescription )
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
UIApplication.shared.applicationIconBadgeNumber = 0
alertRemoteNotification(userInfo as NSDictionary)
}
//Code for showing alert when in foreground
func alertRemoteNotification(_ userInfo : NSDictionary)
{
if UIApplication.shared.applicationState == .active {
if let aps = userInfo as? NSDictionary {
if let apsDidt = aps.value(forKey: "aps") as? NSDictionary {
if let alertDict = apsDidt.value(forKey: "alert") as? NSDictionary {
if let notification_type = alertDict.value(forKey: "name") as? String {
if let notification_Message = alertDict.value(forKey: "body") as? String {
let alert = UIAlertController(title: notification_type.capitalized + " Alert", message: notification_Message, preferredStyle: UIAlertControllerStyle.alert)
let okayBtn = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
// When Okay
UIApplication.shared.applicationIconBadgeNumber = 0
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.removeAllDeliveredNotifications() // To remove all delivered notifications
center.removeAllPendingNotificationRequests()
} else {
// Fallback on earlier versions
UIApplication.shared.cancelAllLocalNotifications()
}
let rootViewController = self.window!.rootViewController as! UINavigationController
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let dashBoardVC = mainStoryboard.instantiateViewController(withIdentifier: "DashBoardVC") as! DashBoardVC
rootViewController.pushViewController(dashBoardVC, animated: false)
})
let cancelBtn = UIAlertAction(title: "Cancel", style: .default, handler: { (action) -> Void in
UIApplication.shared.applicationIconBadgeNumber = 0
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.removeAllDeliveredNotifications() // To remove all delivered notifications
center.removeAllPendingNotificationRequests()
} else {
// Fallback on earlier versions
UIApplication.shared.cancelAllLocalNotifications()
}
})
alert.addAction(okayBtn)
alert.addAction(cancelBtn)
self.window?.rootViewController!.present(alert, animated: true, completion: nil)
}
}
}
}
}
}
else {
let rootViewController = self.window!.rootViewController as! UINavigationController
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let dashBoardVC = mainStoryboard.instantiateViewController(withIdentifier: "DashBoardVC") as! DashBoardVC
rootViewController.pushViewController(dashBoardVC, animated: false)
}
}
//Delegate methods
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.sound, .alert, .badge])
UIApplication.shared.applicationIconBadgeNumber = 0
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo as NSDictionary
completionHandler()
self.alertRemoteNotification(userInfo as NSDictionary)
}
I could able to access the responce after tapping notification banner but the actual issue is when i'm in foreground i need to show an alert with the notification responce without tapping on notification banner. Please let me know how can get responce without tapping on notification banner.
iOS 10+ Provides delegate userNotificationCenter:willPresentNotification:withCompletionHandler
Asks the delegate how to handle a notification that arrived while the
app was running in the foreground.
And this will call only if app opened.
Also you can use CONTENT-AVAILABLE=1 for triggering methods.
FLOW:(Without Taping Notification, content-available:1)
App Opened State:- willPresentNotification(ios10+) -> didReceiveRemoteNotification:fetchCompletionHandler
App in Background:- didReceiveRemoteNotification:fetchCompletionHandler
App Closed:- You won't get notification data unless, the app opened by clicking Notification
Alternate method: Using Rich Notification
You can use Notification Extensions to create custom push notifications(contents including images/videos). Notification Service Extension & Notification Content Extension used to achieve this. mutable-content:1 required to trigger this. Here you can download images, get data, etc. [But the data can be shared with App ONLY through UserDefaults(App Groups), correct me if i'm wrong]
You could search for some random tutorials
Create notification service extension to process notification data. you will get 30seconds to process pushnotification via notification service extension
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: #escaping (UNNotificationContent) -> Void) {
if let copy = request.content.mutableCopy() as? UNMutableNotificationContent {
// Process your notification here
contentHandler(copy)
}
}
Hope this will help you
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.sound, .alert, .badge])
UIApplication.shared.applicationIconBadgeNumber = 0
// Added This line
alertRemoteNotification(notification.request.content.userInfo as NSDictionary)
}
Working without any issues.

I am working on push notification with firebase. and my "didReceiveRemoteNotification" function is not called

I am working on push notification with firebase. and my "didReceiveRemoteNotification" function is not called.i do not know why my function is not called and also payload data is not recieved in console.please resolve my issue.Thanks in advance.
**Here is my code:**
FirebaseApp.configure()
Messaging.messaging().shouldEstablishDirectChannel = true
// [START register_for_notifications]
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound],
categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
// [END register_for_notifications]
// Add observer for InstanceID token refresh callback.
NotificationCenter.default
.addObserver(self, selector:
#selector(AppDelegate.tokenRefreshNotification),
name: NSNotification.Name.InstanceIDTokenRefresh,
object: nil)
#objc func tokenRefreshNotification(_ notification: UIViewController)
{
Messaging.messaging().subscribe(toTopic: "Testing")
}
func application(_ application: UIApplication, didReceiveRemoteNotification
userInfo: [AnyHashable : Any])
{
print("userInfo\(userInfo)")
}
import UserNotifications
in didFinishLaunchingWithOptions
if #available(iOS 10, *) {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
application.registerForRemoteNotifications()
} else {
application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
}
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
application.registerForRemoteNotifications()
registerForPushNotifications(application: application)
//MARK: pushNotifications methods:
func registerForPushNotifications(application: UIApplication) {
if #available(iOS 10.0, *){
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(granted, error) in
if (granted) {
UIApplication.shared.registerForRemoteNotifications()
} else{
//Do stuff if unsuccessful...
}
})
} else { //If user is not on iOS 10 use the old methods we've been using
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
print(response.notification.request.content.userInfo)
let dic = response.notification.request.content.userInfo as NSDictionary
if let aps = dic["aps"] as? [String: Any] {
print(aps)
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
print(notification.request.content.userInfo)
let dic = notification.request.content.userInfo as NSDictionary
if let aps = dic["aps"] as? [String: Any] {
print(aps)
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
// Print notification payload data
print("Push notification received: \(data)")
}
Try using the didreceiveremotenotification completionhandler method. Don't forget to enable the push notifications capability in capabilities tab of your project settings section.

How to detect "clear" notifications

if more than a minute pass from the time a user notification arrived to notification center, there is a "clear" option to dismiss one or more notifications at once from notification center.
How the iOS OS notify that the user tapped on "clear" to dismiss several notifications together?
Van's anwser goes straight into the right direction, but we do not need to implement the custom action to get what the question giver wanted.
If you create the category and pass it to the UNUserNotificationCenter you get a callback on the delegates didReceive function even if the user tabbed on the builtin Clear Button or the "X" Button on the content extension. The ResponeIdentifier will then be response.actionIdentifier == UNNotificationDismissActionIdentifier.
The Category must be something like that:
//Create the category...
UNNotificationCategory(identifier: "YourCustomIdentifier",
actions: [], intentIdentifiers: [], options: .customDismissAction)
//... and pass it to the UNUserNotificationCenter
UNUserNotificationCenter.current().setNotificationCategories(notificationCategories)
The category triggers the magic in the iOS framework and suddenly you get callbacks in your delegate.
The delegate function should look like:
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
if response.actionIdentifier == UNNotificationDismissActionIdentifier {
// notification has been dismissed somehow
}
completionHandler()
}
its possible from iOS 10 and above with implementation of custom notification, you will need to work with UNNotificaitons
private func registerForRemoteNotificaiton(_ application: UIApplication) {
// show the dialog at a more appropriate time move this registration accordingly.
// [START register_for_notifications]
if #available(iOS 10.0, *) {
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {(granted, error) in
if granted {
DispatchQueue.main.async(execute: {
UIApplication.shared.registerForRemoteNotifications()
})
}
})
configureUserNotification()
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
// For iOS 10 data message (sent via FCM)
Messaging.messaging().delegate = self as MessagingDelegate
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
// [END register_for_notifications]
}
private func configureUserNotification() {
if #available(iOS 10.0, *) {
let action = UNNotificationAction(identifier: UNNotificationDismissActionIdentifier, title: "Cancel", options: [])
//let action1 = UNNotificationAction(identifier: "dismiss", title: "OK", options: [])
let category = UNNotificationCategory(identifier: "myNotificationCategory", actions: [action], intentIdentifiers: [], options: .customDismissAction)
UNUserNotificationCenter.current().setNotificationCategories([category])
} else {
// Fallback on earlier versions
}
}
call registerForRemoteNotificaiton method from appdelegate's didFinishLaunching method.
Then you will need to implement UNUserNotificationCenterDelegate in appdelegate.
and then you will get the clear (here "Dismiss" as we added in action name)
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
if response.actionIdentifier == UNNotificationDismissActionIdentifier {
//user dismissed the notifcaiton:
}
completionHandler()
}
find more information here
First you should set the UNUserNotificationCenterDelegate:
import UserNotifications
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
return true
}
then user the delegate functinos
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
switch response.actionIdentifier {
case UNNotificationDismissActionIdentifier:
// Do whatever you want to do on dismiss action, when user clear the notification
break
case UNNotificationDefaultActionIdentifier:
// Do whatever you want to do on tap action, when user tap on notification and your application will open
break
default:
break
}
}
}

Firebase sends topic notifications to every users on iOS

Hi I'm using firebase to manage the notifications, but when I handle a message with my index.js, sendToTopic function send notification without check the topic.
So I've tried to send a message with firebase's console, and it's the same.
During the users registration, on iOS environment, I don't subscribe user to anything, but still receives the notification.
My index.js is:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('topics/{code}/')
.onWrite(event =>{
var request = event.data.val();
var signals = request.signals;
var index = Object.keys(signals).length-1;
var lastSignalKey = Object.keys(signals)[index];
var lastSignal = signals[lastSignalKey];
var code = lastSignal.code;
var uid = lastSignal.uid;
var type = lastSignal.type;
var when = lastSignal.when;
var sound = "sound.aiff";
var payload = {
notification : {
body : "mMessage",
title : "MoVeng",
"sound" : sound
},
data: {
uid: uid,
code: code,
type: type,
when: when
}
};
let signal = admin.database()
.ref("topics/"+
code + "/"+
type+ "/"+
uid);
signal.remove();
admin.messaging().sendToTopic(code, payload).then(function(response){
console.log("Success: ",response);
})
.catch(function(error){
console.log("Error: ",error);
})
});
I've tried to googling, but no one has this problem.
I don't understand why notifications come in if no ID, no handler, no token are passed through the notification, just the topic name, and sendToTopic doesn't do what it should do.
this is my appDelegate code, if it can help someone to help me:
import UIKit
import Firebase
import FirebaseDatabase
import UserNotifications
import FirebaseMessaging
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {
public static var active = false
var window: UIWindow?
let sharedInstance = FirebaseAPI()
let defaults = UserDefaults.standard
var data : NSDictionary?
override init(){
super.init()
let logs = defaults.object(forKey: "logs")
print(String(describing: logs))
UIFont.overrideInitialize()
}
func getData() -> NSDictionary?{
return data
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]?) -> Bool {
if let options = launchOptions
{
let params = options[.remoteNotification] as! NSDictionary
data = params
}
else
{
application.applicationIconBadgeNumber = 0
}
FirebaseApp.configure()
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound]) { (authenticated, error) in
}
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
sharedInstance.findCode(forUser: (Auth.auth().currentUser?.uid)!) { (code) in
if let notificationCode = notification.request.content.userInfo["code"] as! String?
{
if (notificationCode.isEqual(code))
{
completionHandler([.badge, .alert, .sound])
}
}
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
let request = response.notification.request
print("mah")
if response.actionIdentifier == "moveng"
{
let whoSignaledMe = request.content.userInfo["whoSignaledMe"] as? String
let signal = Signal.getAnswer(code: whoSignaledMe!)
FirebaseAPI.getNotificationKey(forUser: whoSignaledMe!,
ofType: "answers").setValue(signal.get());
}
completionHandler()
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
completionHandler(UIBackgroundFetchResult.newData)
}
}
Where am I wrong?

UNNotificationAction not showing in remote notification

I am implemetaing actionable remote notification but action button are not showing while notification come.
Payload
{"aps":{"alert":"Testing..
(11)","badge":1,"sound":"default"},"category":"newnote"}
My Code
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.configureUserNotifications()
self.registerForRemoteNotification()
return true
}
func registerForRemoteNotification() {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil{
UIApplication.shared.registerForRemoteNotifications()
}
}
func configureUserNotifications() {
let acceptAction = UNNotificationAction(identifier:
"accept", title: "✅ Accept note", options: [])
let rejectAction = UNNotificationAction(identifier:
"reject", title: "❌ Reject note", options: [])
let category =
UNNotificationCategory(identifier: "newnote",
actions: [acceptAction,rejectAction],
intentIdentifiers: [],
options: [])
UNUserNotificationCenter.current()
.setNotificationCategories([category])
}
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Registration for remote notifications failed")
print(error.localizedDescription)
}
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("Registered with device token: \(deviceToken.hexString)")
self.deviceToken = deviceToken.hexString
}
//Called when a notification is delivered to a foreground app.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
print("User Info = ",notification.request.content.userInfo)
completionHandler([.alert, .badge, .sound])
}
//Called to let your app know which action was selected by the user for a given notification.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
print("User Info = ",response.notification.request.content.userInfo)
print("Response received for \(response.actionIdentifier)")
if response.actionIdentifier == "accept" {
}
else if response.actionIdentifier == "reject" {
}
completionHandler()
}
I think if you move UNUserNotificationCenter.current()
.setNotificationCategories([category]) to your registerForRemoteNotification function, the problem will resolve. Something like this:
if #available(iOS 8.0, *) {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: Set([category]))
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}

Resources