Push is being received while app is in the background killed by the user, when the user hits the push notification it opens the app and it doesn't crash but it is closed immediately.
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// With swizzling disabled you must let Messaging know about the message, for Analytics
Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
print("The userInfo is: \(userInfo)")
completionHandler(UIBackgroundFetchResult.newData)
}
The previous method is not even called, or may be it is but I don't know how to debug it, since the application is not running.
Here's the notification object that I send via the server:
apns: {
payload: {
aps: {
alert: {
title: messageObject.authorName,
body: messageObject.content,
},
sound: "notification.wav",
category: "ChatViewController"
}
}
}
That is what is send via the server. The notifications work when the application is in background and not killed, or when the application is in foreground.
I think so when user click on the notification while your application is killed or in background or foreground, below method would be executed. And you have to test it one by one.
First of all check that whether yo are able to see the popup as soon as the application runs when you click on notification. Just copy, paste this code in your AppDelegate Class and comment your didReceiveRemoteNotification method and then check whether your application crash or not.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
guard let object = response.notification.request.content.userInfo as? [String : AnyObject] else {
return
}
self.normalPopup()
}
/// Alert Popup, if user not exist in our database.
func normalPopup() {
let alert = UIAlertController(title: "Test", message: "Show pop up window.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
}))
self.window?.rootViewController?.present(alert, animated: true)
}
If popup window shows, then comment the normalPopup function and replace that function with below code. Then check whether your application crash or not while application killed.
Messaging.messaging().appDidReceiveMessage(userInfo)
Please Lemme know if you are still facing the same issue.
If you use firebase for that first you should define it on application(_ application:, didFinishLaunchingWithOptions:) like underneath:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
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()
Messaging.messaging().delegate = self
FirebaseApp.configure()
return true
}
Also you can Handle notifications when app is ran, with this func:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if let messageID = userInfo["gcm.message_id"] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
and
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
if let messageID = userInfo["gcm.message_id"] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
and you should set new token to Messaging with this method:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
let token = deviceToken.map { String(format: "%02.2hhx", $0)}.joined()
print(token)
}
at the end you can handle notifications with below extension
// [START ios_10_message_handling]
#available(iOS 10, *)
extension AppDelegate: UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
if let messageID = userInfo["gcm.message_id"] {
print("Message ID: \(messageID)")
}
//*************************
// Handle push notification message automatically when app is running
//*************************
print(userInfo)
// Change this to your preferred presentation option
completionHandler([[.alert, .sound]])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo["gcm.message_id"] {
print("Message ID: \(messageID)")
}
//*************************
// Handle push notification message after click on it
//*************************
print(userInfo)
completionHandler()
}
}
Related
I have a problem with FCM push notifications.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Swift.Void)
and
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Swift.Void)
are not called when I receive a push. The notification is generated in my iPhone.
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void)
is called instead but I don't understand why because it's deprecated.
The content of my notification:
{
"to": "FCM Token",
"priority": "high",
"content_available": true,
"notification": {
"sound": "default",
"title": "Test",
"body": "Test",
"description": "Test"
},
"data": {
"id": 123456,
"status": "11",
}
}
In my AppDelegate.swift:
import UIKit
import CoreData
import Firebase
import Fabric
import Crashlytics
import GoogleMaps
import GooglePlaces
import FBSDKLoginKit
import GoogleSignIn
import NotificationBannerSwift
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
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()
Messaging.messaging().delegate = self
Messaging.messaging().shouldEstablishDirectChannel = true
return ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
}
func applicationWillResignActive(_ application: UIApplication) {
pprint(" - applicationWillResignActive - ")
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
AppEvents.activateApp()
}
func applicationDidEnterBackground(_ application: UIApplication) {
pprint(" - applicationDidEnterBackground - ")
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
pprint(" - applicationWillEnterForeground - ")
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
pprint(" - applicationDidBecomeActive - ")
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
pprint(" - applicationWillTerminate - ")
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
private func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
pprint("apns token: ", deviceToken)
Messaging.messaging().apnsToken = deviceToken as Data
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
print(" ")
print("-- New message classique --")
print("Notification received : \(userInfo)")
print(" ")
// Print full message.
print(userInfo)
completionHandler(.noData)
}
// MARK: - UNUserNotificationCenterDelegate methods
extension AppDelegate: UNUserNotificationCenterDelegate {
// FOREGROUND: The method will be called on the delegate only if the application is in the foreground. If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. This decision should be based on whether the information in the notification is otherwise visible to the user.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Swift.Void) {
DispatchQueue.main.async {
// print("will present: ", notification)
// Messaging.messaging().appDidReceiveMessage(notification.request.content.userInfo)
// completionHandler(.alert)
let userInfo = notification.request.content.userInfo
// With swizzling disabled you must let Messaging know about the message, for Analytics
Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
print(" ")
print("Notification received : \(notification)")
print("-- New message from Notification ios10 only --")
print(" ")
guard
let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
let alert = aps["alert"] as? NSDictionary,
let body = alert["body"] as? String,
let title = alert["title"] as? String
else {
// handle any error here
return
}
print("Title: \(title) \nBody:\(body)")
let banner = NotificationBanner(title: title, subtitle: body, style: .success)
banner.show()
// Change this to your preferred presentation option
//completionHandler([])
}
}
// BACKGROUND: The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Swift.Void) {
DispatchQueue.main.async {
print("didReceive")
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo["gcmMessageIDKey"] {
print("Message ID: \(messageID)")
}
print(userInfo)
if let body = userInfo["body"] as? String {
print("inbody")
NotificationCenter.default.post(name: Notification.Name("userInfo"), object: body)
}
//Push().handlePush(info: userInfo)
// Print full message.
print(userInfo)
Messaging.messaging().appDidReceiveMessage(response.notification.request.content.userInfo)
completionHandler()
}
}
}
// MARK: - MessagingDelegate methods
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
//log.info("FCM registration token received = \(fcmToken)")
print("FCM registration token received = \(fcmToken)")
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
//log.info("didReceive message = \(remoteMessage)")
print("didReceive message = \(remoteMessage)")
}
func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) {
print(" - - - FIR Remote message - - - ")
print("%#", remoteMessage.appData)
//Push().handlePush(info: remoteMessage.appData)
}
}
In my Info.plist I have FirebaseAppdelegateProxyEnable set to NO
In capabilities, I have Push Notifications enabled and Remote Notifications are enabled too in Background Mode.
I'm using Xcode 11.1. I have converted my project to Swift 5 (it was created with Swift 3), I have changed the build system to the new one.
I have two targets with this project I don't know if it can be related to my issue.
I try with an empty new project with the same AppDelegate.swift, same bundle identifier and it works.
try this
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
// put your code here
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
// put your code here
}
I have implemented push notification by firebase. Not able to get notifications from background. Having following code in my App delegate,
class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
sleep(3)
IQKeyboardManager.shared.enable = true
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)
}
Messaging.messaging().delegate = self
Messaging.messaging().shouldEstablishDirectChannel = true
UIApplication.shared.registerForRemoteNotifications()
FirebaseApp.configure()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
Messaging.messaging().shouldEstablishDirectChannel = true
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Message Data", remoteMessage.appData)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([.alert])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler()
}
}
And getting print for Message Data at did receive remote Notification
Message Data [AnyHashable("from"): 459345502087, AnyHashable("collapse_key"): www.rwdev.com.TravelSheriff2.1, AnyHashable("notification"): {
body = "Notifications ";
e = 1;
tag = "campaign_collapse_key_4509884114250587926";
title = "Travel Sheriff ";
}]
But I am not able to get push notifications while background and foreground. Even not getting "Message Data" print while app in background.
(Note:Please don't come up with previous stack overflow links and answers have already tried most of them..didnt work out..)
Hey #Aleesha use the request identifier.
I give you example down below follow the code, i hope its worked.
//MARK:- USER NOTIFICATION DELEGATE
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void)
{
print(notification.request.content.userInfo)
if notification.request.identifier == "rig"{
completionHandler( [.alert,.sound,.badge])
}else{
completionHandler([.alert, .badge, .sound])
}
}
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void)
{
//Handle the notification
completionHandler(
[UNNotificationPresentationOptions.alert,
UNNotificationPresentationOptions.sound,
UNNotificationPresentationOptions.badge])
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print(deviceTokenString)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
print(userInfo)
switch application.applicationState {
case .active:
let content = UNMutableNotificationContent()
if let title = userInfo["title"]
{
content.title = title as! String
}
if let title = userInfo["text"]
{
content.body = title as! String
}
content.userInfo = userInfo
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 0.5, repeats: false)
let request = UNNotificationRequest(identifier:"rig", content: content, trigger: trigger)
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().add(request) { (error) in
if let getError = error {
print(getError.localizedDescription)
}
}
case .inactive:
break
case .background:
break
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("i am not available in simulator \(error)")
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
let token = Messaging.messaging().fcmToken
print("FCM token: \(token ?? "")")
}
I'm using FCM server for remote notifications, it worked perfectly with sending and receiving notifications.
My problem is when the device is in the background, this function func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) doesn't called.
Solutions that I've tried:
This function:
userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void)
is called when user tapped on the notification. Otherwise, it's not triggered.
Adding "content-available": true, "priority": "high" to the payload. Also, I tried this value "content-available": 1.
This is my function code:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print("userInfo: \(userInfo)")
completionHandler(.newData);
}
Just adding on accepted answer: in my case the problem was the same, but as I'm sending the Notification through an http "POST" NSMUtableRequest the way to apply the accepted answer was to actually add it in the notification parameters together with sound, badge, tiles etc etc..
let postParams: [String : Any] = [
"to": receiverToken,
"notification": [
"badge" : 1,
"body": body,
"title": title,
"subtitle": subtitle,
"sound" : true, // or specify audio name to play
"content_available": true, // this will call didReceiveRemoteNotification in receiving app, else won't work
"priority": "high"
],
"data" : [
"data": "ciao",
]
]
Hope this will also help others, as I spent a long time trying to figure out how to apply this solution.
Many thanks.
If you are testing with Postman then try changing "content-available": true to "content_available" : true. content-available will send notification but it doesn't call didReceiveRemoteNotification.
All you need to see remote notification in background and foreground and show as alert when app run are this appDelegate.swift that i used in my code:
import Firebase
import UserNotifications
import FirebaseMessaging
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm_message_id"
var deviceID : String!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// [START set_messaging_delegate]
Messaging.messaging().delegate = self
// [END set_messaging_delegate]
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()
FirebaseApp.configure()
Fabric.sharedSDK().debug = true
return true
}
func showNotificationAlert(Title : String , Message : String, ButtonTitle : String ,window : UIWindow){
let alert = UIAlertController(title: Title, message: Message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: ButtonTitle, style: .cancel, handler: nil))
window.rootViewController?.present(alert, animated: true, completion: nil)
}
// [START receive_message] remote notification
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the FCM registration token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
// With swizzling disabled you must set the APNs token here.
// Messaging.messaging().apnsToken = deviceToken
}
}
// [START ios_10_message_handling]
#available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([.alert, .badge, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
if let aps = userInfo["aps"] as? NSDictionary {
if let alert = aps["alert"] as? NSDictionary {
if let title = alert["title"] as? NSString {
let body = alert["body"] as? NSString
showNotificationAlert(Title: title as String, Message: body! as String, ButtonTitle: "Ok", window: window!)
}
} else if let alert = aps["alert"] as? NSString {
print("mohsen 6 =\(alert)")
}
}
// Print full message.
print(userInfo)
completionHandler()
}
}
// [END ios_10_message_handling]
extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
deviceID = fcmToken
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
// [END refresh_token]
// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
// [END ios_10_data_message]
}
The first thing you need to check is the Background Mode > Remote Notification is on. If not, it will not be invoked in the background mode.
Step 1 – Add framework
import UserNotifications
Step 2 – Inherit AppDelegate with UNUserNotificationCenterDelegate
final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {}
Step 3 – Make appropriate changes for registerPushNotifications and call it didFinishLaunchingWithOptions
private func registerPushNotifications() {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.currentNotificationCenter().delegate = self
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert], completionHandler: { granted, error in
if granted {
UIApplication.sharedApplication().registerForRemoteNotifications()
} else {
// Unsuccessful...
}
})
} else {
let userNotificationTypes: UIUserNotificationType = [.Alert, .Badge, .Sound]
let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
}
}
Step 4 – Implement new handlers
// leave this for older versions
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
}
// For iOS10 use these methods and pay attention how we can get userInfo
// Foreground push notifications handler
#available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
if let userInfo = notification.request.content.userInfo as? [String : AnyObject] {
// Getting user info
}
completionHandler(.Badge)
}
// Background and closed push notifications handler
#available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
if let userInfo = response.notification.request.content.userInfo as? [String : AnyObject] {
// Getting user info
}
completionHandler()
}
As you tried i believe every thing , background permission is enable , content-available is the part of payload, you are also receiving notification in active state, last thing will be Power save mode, you need to check is power saving is off; as if you Phone is in power saving mode, then background refresh and other process is gone in limited state, so app will not call didReceivedNotifcation in background.
I am working on ios push notification and need to redirect it to a specific page on tapping it.
How can this functionality be achieved ?
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print("userInfo:-> \(userInfo)")
let redirect_flag = userInfo["redirect_flag"]as! String
if application.applicationState == .inactive {
//MARK: - code here to redirect when app is not in background or inactive
if (UserDefaults.standard.value(forKey: KEY_IS_LOGIN) != nil)
{
switch redirect_flag {
case "1":
print("redirect controller")
case "2":
print("redirect controller")
case "3":
print("redirect controller")
default:
break
}
}
}else {
//MARK: - code here to redirect when app is in background or active mode
switch redirect_flag {
case "1":
print("redirect controller")
case "2":
print("redirect controller")
case "3":
print("redirect controller")
default:
break
}
}
}
To redirect to a specific page when a notification received ,you must first handle received push notification,
To handle recieved push notification follow the steps below:
In didFinishLaunchingWithOptions set messaging delegate to self
Register for remote notification. This shows a permission dialog on first run
You need to handle notification registration for iOS 10 and before
implement didReceiveRemoteNotification to start receiving messaging , here you can handle received data, parse it and redirect ... this will be called when notification tapped for devices that run iOS lower than 10
For iOS 10 and later you can conform to UNUserNotificationCenterDelegate, and implement didReceive method.That's it
Example:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// [START set_messaging_delegate]
Messaging.messaging().delegate = self
// [END set_messaging_delegate]
// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
// [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()
return true
}
Handling Recived messaged :
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
Handle Received notifications for iOS 10 and later:
#available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([.alert, .badge, .sound])
}
//When clicked
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
//You can here parse it, and redirect.
completionHandler()
}
}
In FCM notifications when a user clicks on notification it is redirecting to home page but I want to redirect to a specific page other than home page and the app is in foreground. When it was redirected to specific page the app should read the data in the notification and display the data on the page.
Here is the code that represent the above idea but it redirects to home page and nothing is happening(like display data).
My APPDelegate.class
import UIKit
import Firebase
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
Messaging.messaging().delegate = self as! MessagingDelegate
//Register for notification
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
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 application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
// This function is added here only for debugging purposes and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired with
// the FCM registration token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
// With swizzling disabled you must set the APNs token here.
// Messaging.messaging().apnsToken = deviceToken
}
}
// [START ios_10_message_handling]
#available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([.alert, .badge, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler()
}
}
// [END ios_10_message_handling]
extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
// [END refresh_token]
// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
// [END ios_10_data_message]
}
add this code inside didReceive Response method like that:
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
let storyBoard: UIStoryboard = UIStoryboard(name: "yourStoryboardName", bundle: nil)
let presentViewController = storyBoard.instantiateViewController(withIdentifier: "yourViewControllerStoryboardID") as! YourViewController
presentViewController.yourDict = userInfo //pass userInfo data to viewController
self.window?.rootViewController = presentViewController
presentViewController.present(presentViewController, animated: true, completion: nil)
completionHandler()
}
Application not running
When app is in closed state you should check for launch option in didFinishLaunchingWithOptions
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
var viewController = UIViewController()
if (launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary) != nil {
viewController = storyBoard.instantiateViewController(withIdentifier: "storyboardIdentifier") // user tap notification
}else{
viewController = storyBoard.instantiateViewController(withIdentifier: "storyboardIdentifier") // User not tap notificaiton
}
self.window?.rootViewController = viewController
self.window?.makeKeyAndVisible()
}
Application in Foreground state Here you can redirect on specific viewcontroller
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print full message.
print(userInfo)
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let presentViewController = storyBoard.instantiateViewController(withIdentifier: "storyboardIdentifier") as! YourViewController
presentViewController.yourDict = userInfo //pass userInfo data to viewController
self.present(presentViewController, animated: true, completion: nil)
completionHandler()
}
}
You have to implement two methods for handling the notification, one for when the app is in the background, and the other for when the app has been shut down and is not running.
Inside your AppDelegate, implement the application(_:didFinishLaunchingWithOptions:) -> Bool method. This is for when the app is not running:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?) -> Bool {
if let notificationData = launchOptions?[.remoteNotification] {
// Use this data to present a view controller based
// on the type of notification received
}
return true
}
When your app is in the background, you need to implement the userNotificationCenter(_:didReceive:withCompletionHandler:) method:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
let notificationData = response.notification.request.content.userInfo
// Use this data to present a view controller based
// on the type of notification received
completionHandler()
}