Sound and Badge not working in Push Notifications - ios

I've linked my Swift Storyboard project with Firebase push notifications.
The notifications are currently arriving, but the problem is that the notifications are coming without sound or badge to display.
If I check the notification.request.content.sound or notification.request.content.badge... is displaying nil...
Anyone has face this? Do I missing something in the code to recieve the notification with the sound and badge?
class AppDelegate: UIResponder, UIApplicationDelegate {
var fcmTokenPreviafy: String = ""
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: { _, _ in }
)
application.registerForRemoteNotifications()
Messaging.messaging().delegate = self
return true
}
}
And here are the extensions:
extension AppDelegate: UNUserNotificationCenterDelegate{
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
let userInfo = notification.request.content.userInfo
print(userInfo)
return [[ .alert, .badge, .sound ]]
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
let userInfo = response.notification.request.content.userInfo
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) async -> UIBackgroundFetchResult {
print(userInfo)
return UIBackgroundFetchResult.newData
}
}
extension AppDelegate: MessagingDelegate{
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase registration token: \(String(describing: fcmToken))")
let dataDict: [String: String] = ["token": fcmToken ?? ""]
NotificationCenter.default.post(
name: Notification.Name("FCMToken"),
object: nil,
userInfo: dataDict
)
fcmTokenPreviafy = 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.
}
}

Related

Firebase push notification not showing while App in foreground iOS

I am sending push notification by using FCM and PushTry, While the app is in suspended mode (App is closed) notification is coming but while app in foreground mode (App is open) notification coming but not showing banner.
didReceiveRemoteNotification notification method is calling when app in foreground mode and print data but not showing banner.
Code:-
import UIKit
import FirebaseCore
import FirebaseMessaging
import IQKeyboardManagerSwift
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window : UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
registerForFirebaseNotification(application: application)
return true
}
func registerForFirebaseNotification(application: UIApplication) {
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()
}
}
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase token: \(fcmToken ?? "")")
let dataDict: [String: String] = ["token": fcmToken ?? ""]
NotificationCenter.default.post( name: Notification.Name("FCMToken"),object: nil, userInfo: dataDict )
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
//UNUserNotificationCenterDelegate
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print("APNs received with: \(userInfo)")
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let content = notification.request.content
print("\(content.userInfo)")
completionHandler([.banner, .list, .sound]) // Display notification Banner
}
}
Print:-
APNs received with: [AnyHashable("google.c.sender.id"): 0000000000,
AnyHashable("google.c.fid"): 000000000, AnyHashable("google.c.a.e"): 1,
AnyHashable("aps"): {
alert = {
body = 22eeee;
title = 11;
};
"content-available" = 1;
}, AnyHashable("gcm.message_id"): 00000000]
App Notification Setting Screen:-
ScreenShot
Question: Can someone please explain to me how to show banner when app in foreground mode, I've tried with above code but no results yet. If i'm doing wrong please correct me.
Can someone please explain to me show notification banner?
Any help would be greatly appreciated.
Thanks in advance.

Push notification using FCM does not work but Onesignal

sending push notification from Onesignal working fine but FCM.
【What I`m Doing】
I am implementing push notification using FCM following published documentation from firebase.
【What I have tried】
・checking required Certificates.(verified using Onesignal. receiving push notification from Onesignal is working fine)
・provisioning files is newest.
・Certificates`s password is correct.
・testing is in development environment.(In ad-hoc environment does not work).
・all Related cache for xcode are cleard.
【What I would like to know】
How to receive push notification using FCM and what I`m missing so far.
【codes is below】※ codes review would be huge help and greatful for me please !!
import UIKit
import AVFoundation
import Firebase
import FBSDKCoreKit
import FBSDKLoginKit
import FacebookCore
import FirebaseDatabase
import UserNotifications
import FirebaseMessaging
import OneSignal
import CallKit
import PushKit
import SkyWay
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, CXProviderDelegate, PKPushRegistryDelegate {
override init() {
super.init()
FirebaseApp.configure()
print("\(UUIDs)========UUIDs=======")
print("\(UUID())========UUID=======")
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// PushKit
let registry = PKPushRegistry(queue: nil)
registry.delegate = self
registry.desiredPushTypes = [PKPushType.voIP]
// Converted to Swift 4 by Swiftify v4.1.6781 - https://objectivec2swift.com/
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
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)
}
let token = Messaging.messaging().fcmToken
print("FCM token: \(token ?? "")")
UserDefaults.standard.set(token, forKey: "FCM_TOKEN")
print("Firebase registration token: \(token)")
Messaging.messaging().delegate = self
application.registerForRemoteNotifications()
Messaging.messaging().isAutoInitEnabled = true
let onesignalInitSettings = [kOSSettingsKeyAutoPrompt: false]
OneSignal.initWithLaunchOptions(launchOptions,
appId: "2e92****************a7f",
handleNotificationAction: nil,
settings: onesignalInitSettings)
OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification;
OneSignal.promptForPushNotifications(userResponse: { accepted in
print("User accepted notifications: \(accepted)")
})
return true
}
// Handle updated push credentials
func pushRegistry(registry: PKPushRegistry!, didUpdatePushCredentials credentials: PKPushCredentials!, forType type: String!) {
// Register VoIP push token (a property of PKPushCredentials) with server
}
func application(application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
print("sdfksjkjfksajkdnslfs")
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
UserDefaults.standard.set(fcmToken, forKey: "FCM_TOKEN")
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.
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return SDKApplicationDelegate.shared.application(application,
open: url,
sourceApplication: sourceApplication,
annotation: annotation)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// Print message ID.
if let messageID = userInfo["gcm.message_id"] {
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["gcm.message_id"] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
}
#available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
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)")
completionHandler([.alert, .sound])
}
print(userInfo)
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let messageID = userInfo["gcm.message_id"] {
print("Message ID: \(messageID)")
}
print(userInfo)
}
}

Not able to receive notification from firebase in swift3

I am not able to receive the notification from firebase. I have updated all pods and also uploaded the APNs Certificates for production. In Xcode i am managing the provisioning profile automatically and also enabled push notification, Remote notification(inside Background modes) in capabilities. Notification is enabled in setting section of device.
Here is my code in App delegate.
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: 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 })
// For iOS 10 data message (sent via FCM
Messaging.messaging().delegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
FirebaseApp.configure()
}
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
completionHandler(UIBackgroundFetchResult.newData)
}
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
func applicationDidBecomeActive(_ application: UIApplication) {
Messaging.messaging().connect { error in
}
}
#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
//Here i do my navigation according to notification type
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
}
extension AppDelegate : MessagingDelegate {
//MARK: FCM Token Refreshed
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
let token = Messaging.messaging().fcmToken
let def = UserDefaults.standard
def.setValue(token, forKey: KDeviceToken)
print(def.object(forKey: KDeviceToken) ?? String())
}
// Receive data message on iOS 10 devices while app is in the foreground.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
NSLog("remoteMessage: \(remoteMessage.appData)")
}
}

iOS only received one notification, after that token is unregistered

I have problem when using FCM for iOS. I can only receive 1 notification per install, after that, iOS stated that my token is unregistered. Have tried to delete the token using InstanceID.instanceID().deleteToken and deleting instanceID using InstanceID.instanceID().deleteID but I still get the same unregistered token. I've also tried to send the notification from FCM console with the same result.
My code in AppDelegate:
let gcmMessageIDKey = "com.ucpmb"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
Messaging.messaging().shouldEstablishDirectChannel = 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)
}
application.registerForRemoteNotifications()
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("delegate", "FCM reg fail")
print("delegate", error.localizedDescription)
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print("Message ID: \(userInfo["gcm.message_id"]!)")
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print("Message ID: \(userInfo["gcm.message_id"]!)")
print(userInfo)
if userInfo["module"] as! String == "pmb_voucher" {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let centerViewController = storyBoard.instantiateViewController(withIdentifier: "PrePilihJurusanViewController") as! PrePilihJurusanViewController
window?.rootViewController = centerViewController
} else if (userInfo["module"] as! String == "pmb_result") {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let centerViewController = storyBoard.instantiateViewController(withIdentifier: "ResultTableViewController") as! ResultTableViewController
window?.rootViewController = centerViewController
}
completionHandler(UIBackgroundFetchResult.newData)
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
print(notificationSettings.types.rawValue)
}
func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
print("Received Local Notification:")
print(notification.alertBody)
}
And for the AppDelegate extension:
#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([])
}
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, didReceiveRegistrationToken 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]
}
I'm currently using Swift 4. Thank you for your help!

Push notifications in Swift iOS

I am working with iOS Swift Notifications Module. I'm not getting the Alert/Banner Notification on the device.
I’m able to get notification when the App is open i.e. in Foreground, but not when app in in Background or Terminated.
Following is my code
import UIKit
import UserNotifications
import Firebase
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate {
var window: UIWindow?
// MARK: - Application Life Cycle
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FIRApp.configure()
askNotificationPermission(application)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.getFirebaseInstaceID(_:)), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
connectToFcm()
return true
}
// MARK:- Push Notification Delegate Methods
#nonobjc func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print(error)
}
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
let appdata = remoteMessage.appData as NSDictionary as! [String: AnyObject]
print(appdata)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// Receive displayed notifications for iOS 10 devices.
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
print("Message ID: \(userInfo["gcm.message_id"]!)")
print("%#", userInfo)
}
// MARK: - Permissions
func askNotificationPermission(_ application: UIApplication) {
if #available(iOS 10.0, *) {
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { (finished, error) in
})
UNUserNotificationCenter.current().delegate = self
FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
}
// MARK: - Firebase Connection Methods
#objc func getFirebaseInstaceID(_ notification: Notification) {
if isNotNull(FIRInstanceID.instanceID().token() as AnyObject?) {
let strFirebaseInstanceID = FIRInstanceID.instanceID().token()! as String
if !strFirebaseInstanceID.isEmpty {
print("Firebase Instance ID - \(strFirebaseInstanceID)")
setString(strValue: strFirebaseInstanceID, forKey: Default.firebaseInstanceID)
NotificationCenter.default.post(name: Notification.Name(rawValue: Notifications.nSendFirebaseID), object: nil)
} else {
setString(strValue: "", forKey: Default.firebaseInstanceID)
}
} else {
setString(strValue: "", forKey: Default.firebaseInstanceID)
}
connectToFcm()
}
func connectToFcm() {
FIRMessaging.messaging().connect { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
}
For iOS 10.*, you need to give push notification present option in completion handler of willPresent notification method list below. Try like this may be helpful.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
Thanks.
As you are sending push using FCM, try sending this payload to FCM for push.
{
"to": "<REGISTRATION_TOKEN_HERE>",
"notification": {
"body": "Yipeee!!! I nailed it",
"sound" : "default"
},
"data" : ""
}
I forgot to add this method
didReceiveRemoteNotification

Resources