Recently I stopped receiving Firebase Cloud Messaging APNs notifications. I decided to update to latest version of Firebase pods and my AppDelegate.swift had a few functions deprecated so it currently looks like this now:
import UIKit
import SwiftyJSON
import IQKeyboardManagerSwift
import Firebase
import FirebaseInstanceID
import FirebaseMessaging
import UserNotifications
import AVFoundation
import Crittercism
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
var isPulltoRefreshInProgress: Bool = Bool(false)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Crittercism.enable(withAppID: Config.sharedInstance.apteligentAppID())
//To find Home Directory
print("Home Directory - \(NSHomeDirectory())")
IQKeyboardManager.shared.enable = true
IQKeyboardManager.shared.enableAutoToolbar = false
IQKeyboardManager.shared.shouldShowToolbarPlaceholder = false
// IQKeyboardManager.shared.shouldResignOnTouchOutside = true
// UIApplication.shared.statusBarStyle = .lightContent
configureForPushNotification()
registrationForNotification(application: application )
self.startOver()
return true
}
func registrationForNotification(application: UIApplication) {
// iOS 10 support
if #available(iOS 10, *) {
DLog("registrationForNotification")
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
application.registerForRemoteNotifications()
}
else {
application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
Tokens.sharedInstance.isNotificationCame = true
NotificationCenter.default.post(name: NSNotification.Name(NotificationCenterIDs.kPushNotificationReceivedNotification), object:self)
if application.applicationState == UIApplication.State.active {
DLog("App is in foreground when notification received")
// app was already in the foreground
} else {
DLog("App was just brought from background to foreground via PUSH")
// app was just brought from background to foreground via PUSH
self.startOver()
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
// let application = UIApplication.shared
// if(application.applicationState == .active){
// DLog("user tapped the notification bar when the app is in foreground")
if let window = self.window {
if let viewController = UIStoryboard(name: StoryboardControllerIDs.kStoryboardId, bundle: nil).instantiateViewController(withIdentifier: StoryboardController.kNotificationsViewController) as? NotificationsViewController{
if let rootViewController = window.rootViewController as? UINavigationController{
// DLog("Root: " + String(describing: type(of: rootViewController)))
Tokens.sharedInstance.isNotificationCame = true
rootViewController.pushViewController(viewController, animated: true)
}
}
}
// }
// if(application.applicationState == .inactive)
// {
// DLog("user tapped the notification bar when the app is in background")
// }
/* Change root view controller to a specific viewcontroller */
// let storyboard = UIStoryboard(name: "Main", bundle: nil)
// let vc = storyboard.instantiateViewController(withIdentifier: "ViewControllerStoryboardID") as? ViewController
// self.window?.rootViewController = vc
completionHandler()
}
func configureForPushNotification() {
var fileName : String = "GoogleServiceQA-Info"
let currentConfiguration = Bundle.main.object(forInfoDictionaryKey: "Config")! as! String
if currentConfiguration.lowercased() == "production" {
fileName = "GoogleServiceProd-Info"
}
let filePath = Bundle.main.path(forResource: fileName, ofType: "plist")!
let options = FirebaseOptions(contentsOfFile: filePath)
FirebaseApp.configure(options: options!)
Messaging.messaging().delegate = self
// if let refreshedToken = InstanceID.instanceID().token() {
// print("InstanceID token: \(refreshedToken)")
// DeviceTokenConstants.deviceToken = refreshedToken
// }
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
DLog("Error fetching remote instange ID: \(error)")
} else if let result = result {
DLog("configureForPushNotification - Remote instance ID token: \(result.token)")
DeviceTokenConstants.deviceToken = result.token
}
}
NotificationCenter.default.addObserver(self, selector:
#selector(tokenRefreshNotification), name:
NSNotification.Name.InstanceIDTokenRefresh, object: nil)
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
//Getting errors in Xcode10 for iOS12
let hexString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
DLog("===DEVICE-TOKEN: \(hexString)")
// In debug mode
Messaging.messaging().apnsToken = deviceToken
Messaging.messaging().setAPNSToken(deviceToken, type: .sandbox)
Messaging.messaging().setAPNSToken(deviceToken, type: .prod)
// In release mode
// InstanceID.instanceID().setAPNSToken(deviceToken, type: InstanceIDAPNSTokenType.prod)
}
// This method will be called when app received push notifications in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void)
{
completionHandler([.alert, .badge, .sound])
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
DeviceTokenConstants.deviceToken = fcmToken
FireBaseToken.didReceived = true
}
#objc func tokenRefreshNotification(_ notification: Notification) {
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
print("Error fetching remote instange ID: \(error)")
} else if let result = result {
print("tokenRefreshNotification - Remote instance ID token: \(result.token)")
DeviceTokenConstants.deviceToken = result.token
let dataDict:[String: String] = ["token": result.token]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
}
}
// Deprecated code
// if let refreshedToken = InstanceID.instanceID().token() {
// print("InstanceID token: \(refreshedToken)")
// DeviceTokenConstants.deviceToken = refreshedToken
// }
// Connect to FCM since connection may have failed when attempted before having a token.
// connectToFcm()
}
Is there something in this code that may prevent the notification from being delivered or is this an external issue outside of the iOS app? I am able to see tokens being printed in my console for the device token and fcm token, so I feel that the setup in the iOS app is not the issue. I ensured that the app notifications were not disabled in my iPhone.
If you are using keyid instead of certification, you can try to change ur debug mode to release mode then you can try to see if you receive push or u can upload to TestFlight and check if you receive the push.
However it’s better to use certification instead keyid that you can use in debug and in release mode.
I don't understand from your code why it doesn't work, have you tried to follow firebase's guide to the letter? It never gave me problems.
Related
So I have a single Xcode project for two iOS app targets that share a common codebase.
The first app was already working and live on the App Store. The second app is just a modified paid version of our earlier app.
Both the apps use Firebase and OneSignal (for push notifications ) and I have downloaded two GoogleServiceInfo.plist files and linked them to their respective targets.
This is my AppDelegate.swift file where I configured Firebase.
import Firebase
import FirebaseMessaging
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var wakeTime : Date = Date() // when did our application wake up most recently?
// To access AppDelegate values
class var shared: AppDelegate {
return (UIApplication.shared.delegate as? AppDelegate) ?? AppDelegate()
}
// To get token for login
var pushRefreshedToken : String {
print(Messaging.messaging().fcmToken)
return Messaging.messaging().fcmToken ?? "token_new_reg"
}
let gcmMessageIDKey = "gcm.message_id"
var notification: Any?
var window: UIWindow?
//this variable is declared so that the app can run on ios 12 or lower running devices, without this it will show black screen.
func applicationWillEnterForeground(_ application: UIApplication) {
// time stamp the entering of foreground so we can tell how we got here
wakeTime = Date()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// OneSignal
let notificationOpenedBlock: OSNotificationOpenedBlock = { result in
// This block gets called when the user reacts to a notification received
let notification: OSNotification = result.notification
print("Message: ", notification.body ?? "empty body")
print("badge number: ", notification.badge)
print("notification sound: ", notification.sound ?? "No sound")
if let additionalData = notification.additionalData {
print("additionalData: ", additionalData)
// Handle additional data
switch UIApplication.shared.applicationState {
case .background, .inactive:
// background, opened from notif
if let tag = additionalData["t"] as? String {
if tag == NotificationRedirectionTags.appstore {
CentralLoadingViewController.redirectionTag = tag
} else {
MiddleViewController.notifTag = tag
}
}
case .active:
// foreground
if let topVC = UIApplication.getTopViewController() {
if let tag = additionalData["t"] as? String {
if tag == NotificationRedirectionTags.vehicleHealth {
print("Going to VH")
let storyboard = UIStoryboard(name: StoryBoards.CarHealthStoryboard, bundle: nil)
let nv = storyboard.instantiateViewController(withIdentifier: Identifiers.MainCarHealthViewController) as! MainCarHealthViewController
topVC.navigationController?.pushViewController(nv, animated: true)
}
if tag == NotificationRedirectionTags.appstore {
if let url = URL(string: "https://apps.apple.com/in/app/scouto/id1495648508") {
UIApplication.shared.open(url)
}
}
}
}
default:
break
}
// Handle action buttons
if let actionSelected = notification.actionButtons {
print("actionSelected: ", actionSelected)
}
if let actionID = result.action.actionId {
//handle the action
if actionID == NotificationRedirectionTags.vehicleHealth {
MiddleViewController.notifTag = actionID
} else if actionID == NotificationRedirectionTags.appstore {
CentralLoadingViewController.redirectionTag = actionID
}
}
}
}
OneSignal.setNotificationOpenedHandler(notificationOpenedBlock)
// Remove this method to stop OneSignal Debugging
OneSignal.setLogLevel(.LL_VERBOSE, visualLevel: .LL_NONE)
// OneSignal initialization
OneSignal.initWithLaunchOptions(launchOptions)
#if MAHINDRA_CW_PRODUCTION
OneSignal.setAppId(appIDOne)
#elseif SCOUTO_PRODUCTION
OneSignal.setAppId(appIDTwo)
#endif
// promptForPushNotifications will show the native iOS notification permission prompt.
// We recommend removing the following code and instead using an In-App Message to prompt for notification permission (See step 8)
OneSignal.promptForPushNotifications(userResponse: { accepted in
print("User accepted notifications: \(accepted)")
})
let str = [NotificationRedirectionTags.appstore, "AppStore"]
if str.contains(UserDefaults.standard.value(forKey: NotificationActionTags.inputText) as? String ?? ""){
if let url = URL(string: "https://apps.apple.com/in/app/scouto/id1495648508") {
UIApplication.shared.open(url)
}
}
LocationService.shared.updatingLocation(completion: { location in
if location != nil{
LocationService.shared.stopUpdatingLocation()
} else {
LocationService.shared.showLocationPermissionsAlert(true)
}
})
// FireBase Setup
FirebaseApp.configure()
// notification
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) { (granted, error) in
guard granted else { return }
print("UNNotificationCenter Auth Granted")
let replyAction = UNTextInputNotificationAction(identifier: "ReplyAction", title: "Reply", options: [])
let openAppAction = UNNotificationAction(identifier: "OpenAppAction", title: "Open app", options: [.foreground])
let quickReplyCategory = UNNotificationCategory(identifier: "QuickReply", actions: [replyAction, openAppAction], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([quickReplyCategory])
print("UNNotificationCategory Set")
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
Messaging.messaging().delegate = self
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching FCM registration token: \(error)")
} else if let token = token {
print("FCM registration token: \(token)")
//self.fcmRegTokenMessage.text = "Remote FCM registration token: \(token)"
}
}
application.registerForRemoteNotifications()
}
//MARK:- Push Notifications
extension AppDelegate {
// DEPRECATED
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("Remote notification: User info 1")
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("User info 2")
print(userInfo)
//completionHandler(UIBackgroundFetchResult.newData)
}
}
// MARK:- Push Notification Handler - UNUserNotificationCenterDelegate
#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("User info 3")
print(userInfo)
// Change this to your preferred presentation option
completionHandler([[.alert, .badge , .sound]])
}
// Notification handler
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)")
}
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print full message.
print("User info 4")
print( )
// Handle text input notification
if response.actionIdentifier == "ReplyAction" {
print("Entered ReplyAction block")
if let textResponse = response as? UNTextInputNotificationResponse {
// Do whatever you like with user text response...
print("----RECEIVING USER NOTIFICATION INPUT ------")
print(textResponse.userText)
if textResponse.userText == NotificationRedirectionTags.appstore || textResponse.userText == "AppStore" {
if let url = URL(string: "https://apps.apple.com/in/app/scouto/id1495648508") {
UIApplication.shared.open(url)
}
}
UserDefaults.standard.setValue(textResponse.userText, forKey: NotificationActionTags.inputText)
return
}
}
// Handle userInfo data
switch UIApplication.shared.applicationState {
case .background, .inactive:
// background, opened from notif
if let tag = userInfo["t"] as? String {
if tag == NotificationRedirectionTags.appstore {
UserDefaults.standard.setValue(tag, forKey: NotificationActionTags.inputText)
}
MiddleViewController.notifTag = tag
}
case .active:
// foreground
if let topVC = UIApplication.getTopViewController() {
if let tag = userInfo["t"] as? String {
// Go to Vehicle Health
if tag == NotificationRedirectionTags.vehicleHealth {
print("Going to VH")
let storyboard = UIStoryboard(name: StoryBoards.CarHealthStoryboard, bundle: nil)
let nv = storyboard.instantiateViewController(withIdentifier: Identifiers.MainCarHealthViewController) as! MainCarHealthViewController
topVC.navigationController?.pushViewController(nv, animated: true)
}
// Go to Live Track
if tag == "os" {
print("Going to Live Track")
let storyboard = UIStoryboard(name: StoryBoards.DashboardStoryboard, bundle: nil)
let nv = storyboard.instantiateViewController(withIdentifier: Identifiers.LiveTrackingViewController) as! LiveTrackingViewController
topVC.navigationController?.pushViewController(nv, animated: true)
}
}
}
default:
break
}
completionHandler()
}
}
//MARK: MessagingDelegate FCM -> Recieve message from FCM
extension AppDelegate : MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase registration token: \(fcmToken)")
let lokenFCM : String = fcmToken ?? "token_new_reg"
let dataDict:[String: String] = ["token": lokenFCM]
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 message data", remoteMessage.appData)
// }
}
I have uploaded the same APNS key to Firebase for both the apps in Project settings.
However, the issue is that I am able to receive notifications only on one app and I am not able to receive notifications in the second app.
I have checked the code multiple times but cannot seem to figure out what is going wrong at all.
Please kindly have a look at the code and provide me with some suggestions on what I may be doing wrong. Your help is highly appreciated & thank you!
I'm trying to send push notifications to the iPhone 6s I am using for testing. I've followed through the Firebase documentation and I can't seem to get a notification arrive to the phone. When I try to send a test notification with the FCM token I get after registering, it is classed as "sent" on the firebase console but not "received".
The minimum software version for the app is iOS 13 so I haven't added the deprecated functions for the notification service.
I've tried:
Disabling and reenabling the push notification and background task capabilities in xcode
Created new certificates and provisioning profiles using the capabilities
Uninstalling the app from the phone and reinstalling it
Setting FirebaseAppDelegateProxyEnabled to NO and YES in the Info.plist file
Writing and running the cloud function that will be used to send the notification which runs as "ok" according to the firebase console
Cleaning the build folder
Using all of the tokens that are returned on registering
Any help would be greatly appreciated,
Thanks in advance :)
App Delegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
db = Firestore.firestore()
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
print("granted: (\(granted)")
}
application.registerForRemoteNotifications()
Messaging.messaging().delegate = self
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
print("Error fetching remote instance ID: \(error)")
} else if let result = result {
print("Remote instance ID token: \(result.token)")
}
}
GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
GIDSignIn.sharedInstance().delegate = self
GADMobileAds.sharedInstance().start(completionHandler: nil)
self.window = UIWindow(frame: UIScreen.main.bounds)
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
UserDefaults.standard.setValue(false, forKey: "backing_up")
let user = Auth.auth().currentUser
let email = user?.email
let password = UserDefaults.standard.string(forKey: "password")
let setup = UserDefaults.standard.bool(forKey: "accountSetup")
let credential = EmailAuthProvider.credential(withEmail: email ?? "", password: password ?? "")
user?.reauthenticate(with: credential)
if (user?.isEmailVerified ?? false) && setup {
let homeVC = mainStoryboard.instantiateViewController(withIdentifier: "MainViewController")
self.window?.rootViewController = homeVC
self.window?.makeKeyAndVisible()
} else {
do {
try Auth.auth().signOut()
} catch let signOutError as NSError {
print ("Error signing out: %#", signOutError)
}
let loginVC = mainStoryboard.instantiateViewController(withIdentifier: "LoginViewController")
self.window?.rootViewController = loginVC
self.window?.makeKeyAndVisible()
}
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
Messaging.messaging().apnsToken = deviceToken
Messaging.messaging().setAPNSToken(deviceToken, type: .prod)
Messaging.messaging().setAPNSToken(deviceToken, type: .sandbox)
UserDefaults.standard.synchronize()
print("token: \(token)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("failed to register for remote notifications with with error: \(error)")
}
// If in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Print message ID.
print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print("%#", userInfo)
completionHandler([.alert, .sound])
}
// If in background
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
print("handling notification")
if let notification = response.notification.request.content.userInfo as? [String:AnyObject] {
let message = parseRemoteNotification(notification: notification)
print(message as Any)
}
completionHandler()
}
private func parseRemoteNotification(notification:[String:AnyObject]) -> String? {
if let identifier = notification["identifier"] as? String {
return identifier
}
return nil
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken 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.
}
FINALLY! I tried to fix the issue by just starting from scratch and began creating another app. Halfway through the process, I found that I hadn't uploaded a .p8 file to Firebase for the app I was trying to get notifications to work for (I thought I had but apparently not).
If you have the same problem, check if your app is properly registered with Firebase on the console for cloud messaging!
Push notifications not working at all. I have tried all the possible measures so far:
This is the code that i have tried:
In didFinishLaunchingWithOptions
FirebaseApp.configure()
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.badge, .alert, .sound]) {
(granted, error) in
if granted {
DispatchQueue.main.async {
application.registerForRemoteNotifications()
//UIApplication.shared.registerForRemoteNotifications()
}
} else {
//print("APNS Registration failed")
//print("Error: \(String(describing: error?.localizedDescription))")
}
}
} else {
let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
let setting = UIUserNotificationSettings(types: type, categories: nil)
application.registerUserNotificationSettings(setting)
application.registerForRemoteNotifications()
//UIApplication.shared.registerForRemoteNotifications()
}
Then the register and fail method:
private func application(application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
Messaging.messaging().apnsToken = deviceToken as Data
print("Registered Notification")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print(error.localizedDescription)
print("Not registered notification")
}
#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["gcm.message_id"] {
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["gcm.message_id"] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler()
}
}
Note:
I have tried it on real device no push notifications so far.
I have double checked the certificates and regenerated the provisioning file after turning on the push notifications in
capabilities.
I have also added background modes -> remote notifications on.
I have tried with legacy build also no luck.
I have tried reinstalling apps many times not working.
FirebaseAppDelegateProxyEnabled is set to NO in plist still no luck.
Also updated the pods still no luck.
.p12 certificate is at the firebase console, still not working.
Trying from last 1 week with different projects with different authentication methods with Apple key i have also tried still no luck.
here is the code i have used to generate push notification hope this helps you out.
put the whole following code in ur appdelegate.
Imported Libraries
import Firebase
import FirebaseMessaging
import UserNotifications
import FirebaseInstanceID
import UserNotifications
add MessagingDelegate to ur appdelegate.
then
In didFinishLaunchingWithOptions
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: { (bool, err) in
})
} else {
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
UIApplication.shared.applicationIconBadgeNumber = 0
FirebaseApp.configure()
// [START set_messaging_delegate]
Messaging.messaging().delegate = self
let token = Messaging.messaging().fcmToken
print("FCM token: \(token ?? "")")
Then Add these Two function
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)
// put your json parameters here Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
if let msg = userInfo["desc"] as? String
{
let title = userInfo["noti_title"] as? String
createNotification(message: msg, title: title ?? "" )
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func createNotification(message: String, title: String) {
let content = UNMutableNotificationContent()
content.title = title
content.body = message
let triger = UNTimeIntervalNotificationTrigger(timeInterval: 2, repeats: false )
let request = UNNotificationRequest(identifier: "TextMessage", content: content, trigger: triger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
Then add these functions to get FCMToken
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
// With swizzling disabled you must set the APNs token here.
if let refreshedToken = InstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
}
let tokenT = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
print(tokenT)
guard let token = InstanceID.instanceID().token() else {return}
AppDelegate.DEVICEID = token
print(token)
UserDefaults.standard.set(token, forKey: "token")
connectToFCM()
}
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
guard let newToken = InstanceID.instanceID().token() else {return}
AppDelegate.DEVICEID = newToken
UserDefaults.standard.set(newToken, forKey: "token")
connectToFCM()
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
print(remoteMessage.appData["notification"]!)
// let info = response.notification.request.content.userInfo
// if let message = info["messages"] {
// print(message)
// }
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
UserDefaults.standard.set(fcmToken, forKey: "token")
}
then add the following extention in your app delegate
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(userInfo)
// Change this to your preferred presentation option
completionHandler([.alert,.badge,.sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
let application = UIApplication.shared
if(application.applicationState == .active){
print("user tapped the notification bar when the app is in foreground")
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
// let layout = UICollectionViewFlowLayout()
window?.rootViewController = UINavigationController(rootViewController: NotificationViewController())
}
if(application.applicationState == .inactive)
{
print("user tapped the notification bar when the app is in background")
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
// let layout = UICollectionViewFlowLayout()
window?.rootViewController = UINavigationController(rootViewController: NotificationViewController())
}
/* Change root view controller to a specific viewcontroller */
// let storyboard = UIStoryboard(name: "Main", bundle: nil)
// let vc = storyboard.instantiateViewController(withIdentifier: "ViewControllerStoryboardID") as? ViewController
// self.window?.rootViewController = vc
completionHandler()
}
func connectToFCM()
{
Messaging.messaging().shouldEstablishDirectChannel = true
}
func initializeNotificationServices() -> Void {
let settings = UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
// This is an asynchronous method to retrieve a Device Token
// Callbacks are in AppDelegate.swift
// Success = didRegisterForRemoteNotificationsWithDeviceToken
// Fail = didFailToRegisterForRemoteNotificationsWithError
UIApplication.shared.registerForRemoteNotifications()
}
}
hoping this will help you out.
I am using FCM for push notification. FCM is connected, device is registered successfully and I am able to print device token but the device is not receiving notification.
In general -> capabilities tab -> enabled push notification and remote notification in back ground mode.
Here registering device for remote notification.
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
let trimEnds:String! = {
deviceToken.description.trimmingCharacters(
in: CharacterSet(charactersIn: "<>"))
}()
let cleanToken:String! = {
trimEnds.replacingOccurrences(of: " ", with: "")
}()
let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
print(token)
UserDefaults.standard.set(token, forKey: "deviceToken")
UserDefaults.standard.synchronize()
#if DEBUG
//For Firebase
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
#else
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.prod)
#endif
print("Device Token:", token)
}
Here I called didReceiveRemoteNotification method to receive notification on the registered device:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print("-=-=-=-=-\nDid receive notification\n-=-=-=-",userInfo)
print("-=-=-=-=-\n")
NotificationCenter.default.post(name: Notification.Name(rawValue: "notification_recieved"), object: nil)
if userInfo.index(forKey: "chat_id") != nil {
print("messag push")
if (AppUtility?.hasValidText(User.userID))! {
//let friendImage = userInfo["path"] as! String
let chatID = userInfo["chat_id"] as! String
let friendId = userInfo["to"] as! String
let unRead = userInfo["unread"] as! String
print(unRead)
UnReadMsgs = unRead
let dictAPS = userInfo["aps"] as! NSDictionary
let dict = dictAPS["alert"] as! NSDictionary
let friendName = dict["title"] as! String
let friendMsg = dict["body"] as! String
if(UIApplication.shared.applicationState == UIApplicationState.active){
print("app is Active")
if let wd = self.window {
var VC = wd.rootViewController
if(VC is UINavigationController){
VC = (VC as! UINavigationController).visibleViewController
if(VC is ChatViewController!){
print("Chat Screen")
let chatVC : ChatViewController = VC as! ChatViewController
if chatVC.chatId == chatID{
print("Same Chat")
self.clearChatWithChatID(chatID)
}else{
CustomNotificationView.showNotificationPopUp(self.window!, name: friendName, msg: friendMsg, image: "", chat: chatID, friendID: friendId)
playSound()
print("Other Chat")
}
}else{
let nc = NotificationCenter.default
nc.post(name: Notification.Name(rawValue: "MessageGet"),
object: nil,
userInfo: ["unRead":unRead,
"date":Date()])
CustomNotificationView.showNotificationPopUp(self.window!, name: friendName, msg: friendMsg, image: "", chat: chatID, friendID: friendId)
playSound()
print("Other Screen")
}
}
}
}else{
print("app is in BG")
var vc:ChatViewController!
vc = ChatViewController(nibName: "ChatViewController", bundle: nil)
vc.chatId = chatID
vc.otherUserId = friendId
vc.otherUserName = friendName
vc.channelRef = self.channelRef.child("\(chatID)")
vc.friendImageLink = "\(resourceUrl)\("")"
let nav = UINavigationController(rootViewController: vc)
nav.isNavigationBarHidden = false
if let wd = self.window {
var VC = wd.rootViewController
if(VC is UINavigationController){
VC = (VC as! UINavigationController).visibleViewController
}
VC!.present(nav, animated: false, completion: {
})
}
}
}
}else{
let val = userInfo["aps"] as! [String:AnyObject];
let alert = NSString(string: val["alert"] as! String)
if(UIApplication.shared.applicationState == UIApplicationState.inactive || UIApplication.shared.applicationState == UIApplicationState.background)
{
showUserInfo(application, didReceiveRemoteNotification: userInfo)
}
else
{
print("top most vc \(String(describing: UIApplication.shared.keyWindow!.rootViewController!.topMostViewController().presentingViewController)) and presentedvc \(String(describing: UIApplication.shared.keyWindow!.rootViewController!.topMostViewController().presentedViewController))")
if UIApplication.shared.keyWindow!.rootViewController!.topMostViewController() is NYAlertViewController{
let newAlert = AppUtility?.getDisplayAlertController(title: "FitFlow", messageText: alert as String)
let nvVc = UIApplication.shared.keyWindow!.rootViewController!.topMostViewController().presentedViewController
nvVc?.present(newAlert!, animated: true, completion: nil)
return
}
AppUtility?.displayAlert(title:"FitFlow", messageText: alert as String,UIApplication.shared.keyWindow!.rootViewController!.topMostViewController())
}
}
}
I have tested by keeping breakpoints, it does not called didReceiveRemoteNotification method at all. How to receive push notification using above method?
I was also stuck with this earlier.
This requires FCM token, and not the APNS token.
To do so,
Your AppDelegate class needs to have these -
import Firebase
import UserNotifications
import FirebaseMessaging
class AppDelegate: UIResponder,
UIApplicationDelegate,
UNUserNotificationCenterDelegate,
FIRMessagingDelegate {
}
Then subscribe the messaging delegate in didFinishLaunchingWithOptions
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
GIDSignIn.sharedInstance().clientID =
"Your client id"
DispatchQueue.main.async {
FIRApp.configure()
}
FIRMessaging.messaging().remoteMessageDelegate = self
if #available(iOS 10, *) {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
application.registerForRemoteNotifications()
}
// iOS 9 support
else if #available(iOS 9, *) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
// iOS 8 support
else if #available(iOS 8, *) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
// iOS 7 support
else {
application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
}
return true
}
// You dont need didRegisterForRemoteNotificationsWithDeviceToken method anymore
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { }
the token you received from the delegate didRegisterForRemoteNotificationsWithDeviceToken is not useful,
You need to use the FIRInstanceID.instanceID().token()
Add below code in your applicationDidBecomeActive, this will check for FCM token refreshes, and handle that elegantly.
func applicationDidBecomeActive(_ application: UIApplication) {
NotificationCenter.default.addObserver(self, selector:
#selector(tokenRefreshNotification), name:
NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
}
#objc func tokenRefreshNotification(notification: NSNotification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
UserDefaults.standard.set(refreshedToken, forKey: "deviceToken")
self.sendFCMTokenToServer(token: refreshedToken)
}
/*
Connect to FCM since connection may
have failed when attempted before having a token.
*/
else {
connectToFcm()
}
}
func updatePushNotificationWebservice() {
/*
if you want to save that token on your server
Do that here.
else use the token any other way you want.
*/
}
func connectToFcm() {
FIRMessaging.messaging().connect { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(String(describing: error))")
}
else {
print("Connected to FCM.")
/*
**this is the token that you have to use**
print(FIRInstanceID.instanceID().token()!)
if there was no connection established earlier,
you can try sending the token again to server.
*/
let token = FIRInstanceID.instanceID().token()!
self.sendFCMTokenToServer(token: token)
}
}
}
For debugging use the token obtained from FIRInstanceID.instanceID().token()!, and use the push notification firebase console with same token in the >project>Cloud messaging tab.
https://console.firebase.google.com/u/0/
Setting priority to high from backend solves my problem.
Please check from firebase console->cloud messaging(down left item) to send push notification.
I am working on an app in which I'm using FCM to send a push notification. I have followed the necessary steps to configure the push notification, i.e generating the certificate to adding entitlements and switch on remote notification in background mode, also uploaded the .p12 certificates with correct password in firebase console. The code I'm using for this is
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
let gcmMessageIDKey = "gcm.message_id"
/// This method will be called whenever FCM receives a new, default FCM token for your
/// Firebase project's Sender ID.
/// You can send this token to your application server to send notifications to this device.
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String)
{
debugPrint("--->messaging:\(messaging)")
debugPrint("--->didRefreshRegistrationToken:\(fcmToken)")
}
#available(iOS 10.0, *)
public func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage)
{
debugPrint("--->messaging:\(messaging)")
debugPrint("--->didReceive Remote Message:\(remoteMessage.appData)")
let action_url = remoteMessage.appData["action_url"]! as! String
if let remoteDiscussion = action_url.slice(from: "https://xxxxxxxx.in/d/", to: "-"){
discussion = remoteDiscussion
window?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "notificationDetailedItemNavigation") as! UINavigationController
}
}
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
debugPrint("###> 1 AppDelegate DidFinishLaunchingWithOptions")
self.initializeFCM(application)
if let token = InstanceID.instanceID().token(){
debugPrint("GCM TOKEN = \(String(describing: token))")
}
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
//FIRMessaging.messaging().disconnect()
debugPrint("###> 1.2 AppDelegate DidEnterBackground")
// self.doServiceTry()
}
func applicationDidBecomeActive(_ application: UIApplication) {
// connectToFcm()
application.applicationIconBadgeNumber = 0
debugPrint("###> 1.3 AppDelegate DidBecomeActive")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error)
{
debugPrint("didFailToRegisterForRemoteNotificationsWithError: \(error)")
}
func application(received remoteMessage: MessagingRemoteMessage)
{
debugPrint("remoteMessage:\(remoteMessage.appData)")
}
func initializeFCM(_ application: UIApplication)
{
print("initializeFCM")
//-------------------------------------------------------------------------//
if #available(iOS 10.0, *) // enable new way for notifications on iOS 10
{
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.badge, .alert , .sound]) { (accepted, error) in
if !accepted
{
print("Notification access denied.")
}
else
{
print("Notification access accepted.")
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
Messaging.messaging().subscribe(toTopic: "/topics/Men")
}
}
}
}
else
{
let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound];
let setting = UIUserNotificationSettings(types: type, categories: nil);
UIApplication.shared.registerUserNotificationSettings(setting);
UIApplication.shared.registerForRemoteNotifications();
}
FirebaseApp.configure()
Messaging.messaging().delegate = self
Messaging.messaging().shouldEstablishDirectChannel = true
NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotificaiton), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)
}
func tokenRefreshNotificaiton(_ notification: Foundation.Notification)
{
if let refreshedToken = InstanceID.instanceID().token()
{
debugPrint("InstanceID token: \(refreshedToken)")
}
// connectToFcm()
}
// func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings)
// {
// debugPrint("didRegister notificationSettings")
// if (notificationSettings.types == .alert || notificationSettings.types == .badge || notificationSettings.types == .sound)
// {
// application.registerForRemoteNotifications()
// }
// }
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if application.applicationState == .active {
if let aps = userInfo["data"] as? NSDictionary {
if let action_url = aps["action_url"] as? String {
// let alert = UIAlertController(title: "Notification", message: alertMessage, preferredStyle: UIAlertControllerStyle.alert)
// let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
// alert.addAction(action)
// self.window?.rootViewController?.present(alert, animated: true, completion: nil)
print(action_url)
}
}
}
completionHandler(.newData)
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
debugPrint("didRegisterForRemoteNotificationsWithDeviceToken: NSDATA")
let token = String(format: "%#", deviceToken as CVarArg)
debugPrint("*** deviceToken: \(token)")
Messaging.messaging().apnsToken = deviceToken as Data
debugPrint("Firebase Token:",InstanceID.instanceID().token() as Any)
Messaging.messaging().subscribe(toTopic: "/topics/Men")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
debugPrint("didRegisterForRemoteNotificationsWithDeviceToken: DATA")
let token = String(format: "%#", deviceToken as CVarArg)
debugPrint("*** deviceToken: \(token)")
// #if RELEASE_VERSION
// FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type:FIRInstanceIDAPNSTokenType.prod)
// #else
// InstanceID.instanceID().setAPNSToken(deviceToken as Data, type:InstanceIDAPNSTokenType.sandbox)
// #endif
Messaging.messaging().apnsToken = deviceToken
debugPrint("Firebase Token:",InstanceID.instanceID().token() as Any)
}
//-------------------------------------------------------------------------//
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 notification
// Print message ID.
Messaging.messaging().appDidReceiveMessage(userInfo)
if let messageID = userInfo["gcm.message_id"] {
debugPrint("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
return true
}
func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
return true
}
//------------------------------------------------------------------
}
// [START ios_10_message_handling]
#available(iOS 10, *)
extension AppDelegate {
// 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()
}
}
On did receive method I've implemented printing the received message and instantiating a viewController which is working fine and whenever I'm sending a notification from postman if the app is running, it is opening up the targeted view controller, but notification is not coming.
I've checked many solutions in StackOverflow but can't figure out the problem. I'm stuck here for like 2 weeks, can anyone please help.
For iOS10 and Above
Use UNUserNotificationCenterDelegate
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
let userInfo:NSDictionary = notification.request.content.userInfo as NSDictionary
print(userInfo)
let dict:NSDictionary = userInfo["aps"] as! NSDictionary
let data:NSDictionary = dict["alert"] as! NSDictionary
RNNotificationView.show(withImage: UIImage(named: "image_Logo_Small"),
title: data["title"] as? String,
message: data["message"] as? String,
duration: 2,
onTap: {
print("Did tap notification")
})
}
This is code shows both native and RNNotifcation usage, i have kept in one code so you can use when it is needed(ios9/ios10).
You will need to change the aspect that needs to be displayed according to your payload.
For below iOS10
The default Push Notification will not be shown when your App is in the foreground.
Push Notification gets displayed when your App is closed or is in Background. For Push to be shown when an app is in the background, you must select "Remote Notification" in "Background Mode".
Now to resolve your concern,
You can create a view identical to push notification,
Display
content of notification in it.
Animate your view same like push
notification, you can also keep action when notification tapped.
If you are looking for Third Party Library then I will recommend: https://github.com/souzainf3/RNNotificationView