how do killed app receive firebase message - ios

Receive notifications in the background and in the foreground.
but I can't get notifications if the application is killed.
open Background fetch and Remote notification from capabilities
installed on certificates via firebase
json file into "content-available" = true, 'priority'=>'high', I added
I want to be able to receive notifications after the application is completely closed
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
var window: UIWindow?
let gcmMessageIDKey = "message_id"
static var DEVICE_ID = String()
var msg_body = ""
var msg_title = ""
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.statusBarStyle = .lightContent
FirebaseApp.configure()
Messaging.messaging().delegate = self
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
func connectToFcm() {
Messaging.messaging().shouldEstablishDirectChannel = true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
if let refreshedToken = InstanceID.instanceID().token() {
AppDelegate.DEVICE_ID = refreshedToken
print("*********")
print("InstanceID token: \(refreshedToken)")
print("*********")
}else{
print("Can't get token device")
}
connectToFcm()
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register for remote notifications with error: \(error)")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print(userInfo)
guard let data: [String: Any] = userInfo as? [String: Any] else {
return
}
let listData = data["notification"] as! String
let jsonData = listData.data(using: .utf8)
do {
let decoder = JSONDecoder()
let dataJson = try decoder.decode(DataNotif.self, from: jsonData!)
msg_body = dataJson.body!
msg_title = dataJson.title!
createNotification(title: msg_title, body: msg_body)
}catch{
print("error")
}
completionHandler(UIBackgroundFetchResult.newData)
}
// messaging
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
if let token = InstanceID.instanceID().token() {
AppDelegate.DEVICE_ID = token
print("*********")
print("Token Instance: \(token)")
print("*********")
}
connectToFcm()
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
guard let data: [String: Any] = remoteMessage.appData as? [String: Any] else {
return
}
let listData = data as! NSDictionary
let jsonData = listData.data(using: .utf8)
do {
let decoder = JSONDecoder()
let dataJson = try decoder.decode(DataNotif.self, from: jsonData!)
msg_body = dataJson.body!
msg_title = dataJson.title!
createNotification(title: msg_title, body: msg_body)
}catch{
print("error")
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
func applicationDidBecomeActive(_ application: UIApplication) {
UIApplication.shared.applicationIconBadgeNumber = 0
connectToFcm()
}
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
completionHandler(.newData)
}
func applicationDidEnterBackground(_ application: UIApplication) {
Messaging.messaging().shouldEstablishDirectChannel = false
print("Disconnect FCM")
}
func createNotification(title: String, body: String) {
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: title, arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: body, arguments: nil)
content.sound = UNNotificationSound.default
content.badge = NSNumber(integerLiteral: UIApplication.shared.applicationIconBadgeNumber + 1)
let request = UNNotificationRequest.init(identifier: "pushNotif", content: content, trigger: nil)
let center = UNUserNotificationCenter.current()
center.add(request)
}
}

You must enable the following :)

Related

Push Notifications not showing when App is in Foreground

I am sending push notifications through my Node.js server and it works fine when the app is in background or closed but if the app is running and is in foreground, then the notifications do not show (although I am able to get the body & message printed in console even in foreground). Here is my app delegate file :
#main
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window : UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
IQKeyboardManager.shared.enable = true
UINavigationBar.appearance().isTranslucent = false
// Override point for customization after application launch.
if #available(iOS 13, *) {
// do only pure app launch stuff, not interface stuff
} else {
self.window = UIWindow()
let token = KeychainWrapper.standard.string(forKey: "token")
if token != nil {
guard let vc = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "navControllerHome") as? UIViewController else {
fatalError("Could not instantiate HomeVC!")
}
window?.rootViewController = vc
} else {
guard let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "startingNavCon") as? UIViewController else {
fatalError("Could not instantiate HomeVC!")
}
window?.rootViewController = vc
}
window?.makeKeyAndVisible()
}
DropDown.startListeningToKeyboard()
registerPushNotifications(application: application)
return true
}
}
func registerPushNotifications(application : UIApplication){
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
guard granted else { return }
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("Successfully registered")
let tokenParts = deviceToken.map{ data in String(format : "%02.2hhx", data)}
let token = tokenParts.joined()
let saveSuccessful: Bool = KeychainWrapper.standard.set((token), forKey: "devicetoken")
print(token)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register for Remote Notifications")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print("Did receive notification")
print("USERINFO",userInfo)
if let aps = userInfo["aps"] as? [String : AnyObject],
let alertDict = aps["alert"] as? String {
print("Body :", alertDict)
}
completionHandler(.newData)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
print("USER NotificationCenter Did Receive")
completionHandler()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
print("userNotificationCenter willPresent")
completionHandler([.banner, .badge, .sound])
}
}
What am I doing wrong, please help.
Missed this :
func registerForPushNotifications(application: UIApplication) {
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound], completionHandler: { (granted, error) in
if granted {
// Register after we get the permissions.
UNUserNotificationCenter.current().delegate = self
}
})
}
Solved now.

Playing sound when receiving notification worked in Development but not in Production

I'm Facing an issue when i Debug Project in Real Device, I'm Getting Notification With Custom Sound, But After making a Build Via Diwai, I'm Not Getting Custom Sound, It Play Default Sound with Notification.I'm Using Firebase. I have Added Custom Sound in Project and added in Bundle Resources as well.
Please Have A look on My Code.
Here's My Code
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate, MessagingDelegate {
var window: UIWindow?
var audioPlayer : AVAudioPlayer?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let content = UNMutableNotificationContent()
content.sound = UNNotificationSound.default
content.sound = UNNotificationSound(named:UNNotificationSoundName(rawValue: "Eigenintro.aiff"))
FirebaseApp.configure()
let audioSessionError: Error? = nil
do {
try AVAudioSession.sharedInstance().setCategory(.playback, options: .mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)
} catch let audioSessionError {
print(audioSessionError.localizedDescription)
}
UIApplication.shared.beginReceivingRemoteControlEvents()
if let audioSessionError = audioSessionError {
print("[AppDelegate] audioSessionError: \(audioSessionError)")
}
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().isAutoInitEnabled = true
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: { [self] _, _ in
Messaging.messaging().delegate = self
}
)
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
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)")
}
}
application.registerForRemoteNotifications()
return true
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase registration token: \(String(describing: fcmToken))")
self.sendDataToServer(token: fcmToken!)
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions)
-> Void) {
let userInfo = notification.request.content.userInfo
defer {
completionHandler([.badge,.sound, .alert])
SoundPlayer.sharedInstance.playSound()
}
print(#function)
print(userInfo)
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
print(#function)
print(userInfo)
completionHandler()
}
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.hexString
print("APNs Device Token: \(token)")
#if DEVELOPMENT
Messaging.messaging().apnsToken = deviceToken
#else
Messaging.messaging().setAPNSToken(deviceToken, type: .prod)
#endif
}
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print(#function)
Messaging.messaging().appDidReceiveMessage(userInfo)
if application.applicationState == .background {
guard let soundURL = Bundle.main.url(forResource: "Eigenintro", withExtension: "aiff") else { return }
//let soundUrl = URL(fileURLWithPath: path)
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
print("[AppDelegate] audioPlayer play call")
audioPlayer!.play()
} catch let audioPlayerError {
print("[AppDelegate] audioPlayerError: \(audioPlayerError)")
}
completionHandler(UIBackgroundFetchResult.newData)
} else {
completionHandler(UIBackgroundFetchResult.noData)
}
}
// foreground
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print("didReceiveRemoteNotification: Received new push Notification")
Messaging.messaging().appDidReceiveMessage(userInfo)
print(#function)
print("didReceiveRemoteNotification: Push notificationMessage is: \(userInfo)")
}
}
My FCM Payload
{
"message": {
"token": "fcm token",
"notification": {
"title": "Breaking News",
"body": "New news story available."
},
"apns": {
"payload": {
"aps": {
"category" : "NEW_MESSAGE_CATEGORY",
"sound": "Eigenintro.aiff"
}
}
}
}
}

PushNotification banner not showing in ios 10.3

I have integrated Push notification on to my project and for some reason the banner appears on when I'm in the background mood and not when I'm in the foreground. I'm sure I've missed something, my code as bellow. Any help would much appreciate.
import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let center = UNUserNotificationCenter.current()
center.delegate = self //not sure this is appropriate
registerForPushNotifications()
}
func registerForPushNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
guard granted else { return }
self.getNotificationSettings()
}
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async(execute: {
UIApplication.shared.registerForRemoteNotifications()
})
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
if let valueInDB = UserDefaults.standard.value(forKey: "Permission_Granted") {
UserDefaults.standard.setValue(token, forKey: "PUSH_TOKEN")
UserDefaults.standard.synchronize()
print("Device Push Token: \(token)")
}
This gets called every time I gets a notification despite if its running on foreground or background. Thus the batch icon gets updated.
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void)
{
print("Recived: \(userInfo)")
completionHandler(.newData)
self.onPushRecieved = MP3ViewController().catchPushNotifications
let notification = JSON(userInfo)
print(notification)
let mediaId = (notification["media_id"]).stringValue
print(mediaId)
var badgeCount = 0
var pushAvailable = false
if let pushCount = UserDefaults.standard.value(forKey: "PUSH_COUNT"){
badgeCount = pushCount as! Int
print(badgeCount)
badgeCount = badgeCount + 1
UIApplication.shared.applicationIconBadgeNumber = badgeCount
}
print(badgeCount)
UserDefaults.standard.setValue(badgeCount, forKey: "PUSH_COUNT")
UserDefaults.standard.synchronize()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
print(isOnBackGround)
if isOnBackGround {
if mediaId != nil{
DispatchQueue.main.async {
let mP3ViewController = storyboard.instantiateViewController(withIdentifier:"MP3ViewController") as! MP3ViewController
mP3ViewController.media_ID = mediaId
self.navigationController?.pushViewController(mP3ViewController, animated:true)
self.isOnBackGround = false
}
}
}else{
print("Running on foreground")
}
}
}
You may want to implement the following function, eg:
public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Swift.Void) {
completionHandler([.badge, .alert, .sound])
}
of this delegate: UNUserNotificationCenterDelegate

UNUserNotificationDelegate method is not getting called and notification is not displaying FCM

I am trying to implement FCM in my Application. I have followed the Documentation https://firebase.google.com/docs/ios/setup and created APN'S key and installed the pod files also.
Firebase
Firebase/Messaging
Now problem is I am getting data in below method:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
FIRMessaging.messaging().appDidReceiveMessage(userInfo)
}
But I am not getting notification and my UNUserNotification Methods are also not getting called.
Below is my code:
import UIKit
import Google
import GoogleSignIn
import Firebase
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate , UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//FireBase
let filePath = Bundle.main.path(forResource: "GoogleService-Info_Firebase", ofType: "plist")
let options = FIROptions(contentsOfFile: filePath)
//registerForPushNotifications()
if #available(iOS 10.0, *) {
let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_,_ in })
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
// For iOS 10 data message (sent via FCM)
FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
//application.registerForRemoteNotifications()
//UNUserNotificationCenter.current().delegate = self
application.registerForRemoteNotifications()
FIRApp.configure(with : options!)
// Add observer for InstanceID token refresh callback.
NotificationCenter.default.addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: .firInstanceIDTokenRefresh,
object: nil)
}
// [START refresh_token]
func tokenRefreshNotification(_ notification: Notification) {
if let refreshToken = FIRInstanceID.instanceID().token() {
Helper.sharedInstance.Print(refreshToken as AnyObject)
Helper.sharedInstance.userDefault.set("\(refreshToken)", forKey: AssessNowKyes.pushToken)
}
//Connect to FCM
connectToFcm()
}
//START connect_to_fcm
func connectToFcm() {
// Won't connect since there is no token
guard FIRInstanceID.instanceID().token() != nil else {
return;
}
// Disconnect previous FCM connection if it exists.
FIRMessaging.messaging().disconnect()
FIRMessaging.messaging().connect { (error) in
if error != nil {
Helper.sharedInstance.Print("Unable to connect with FCM. \(String(describing: error))" as AnyObject)
} else {
Helper.sharedInstance.Print("Connected to FCM." as AnyObject)
}
}
}
}
//MARK :- Notification
extension AppDelegate {
//Request for Notifications
func registerForPushNotifications() {
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
FIRMessaging.messaging().remoteMessageDelegate = self
//Helper.sharedInstance.Print("Permission granted: \(granted)" as AnyObject)
if granted == false {
// Helper.sharedInstance.Print("Permission granted: False in Loop" as AnyObject)
}
}
}
else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
}
}
//User Notification
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
// Play sound and show alert to the user
completionHandler([.alert,.sound])
}
//Recieve response
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
// Determine the user action
switch response.actionIdentifier {
case UNNotificationDismissActionIdentifier:
print("Dismiss Action")
case UNNotificationDefaultActionIdentifier:
Helper.sharedInstance.Print(response.notification.request.content.userInfo as AnyObject)
/*if true == (response.notification.request.content.title).contains("Traffic") {
}
else if (response.notification.request.content.userInfo["type"] as? String)?.contains("Reminder") == true {
}
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [response.notification.request.identifier])
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [response.notification.request.identifier])*/
default:
Helper.sharedInstance.Print("Unknown action" as AnyObject)
}
completionHandler()
}
}.
//MARK :- FCM DidRegisterRemoteNotificationWithDeviceToken
extension AppDelegate {
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
//FIRMessaging.messaging().
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .sandbox)
Helper.sharedInstance.Print(deviceToken as AnyObject)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
Helper.sharedInstance.Print("Unable to register for remote notifications: \(error.localizedDescription)" as AnyObject)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
FIRMessaging.messaging().appDidReceiveMessage(userInfo)
//Helper.sharedInstance.localNotificationTrigger(title: userInfo["title"]! as! String, body: userInfo["message"]! as! String, identifier: userInfo["gcm.message_id"]! as! String)
//0:1504338754994223%0dc014bc0dc014bc
// Print message ID.
/*if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}*/
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
}
Any issue with device or any other thing I am missing? Why I am not getting notification and why UNUserNotification is not working?

iOS with Firebase notification, all not working

What ever I do the notification is not received.
Sending to Android is going fine, sending to iOS is a failure
I am sending from Firebase Console
I am not receiving foreground or background notification
here is the AppDelegate.swift
import UIKit
import Firebase
import FirebaseMessaging
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if #available(iOS 10.0, *) {
UIView.appearance().semanticContentAttribute = .forceLeftToRight
}
FirebaseApp.configure()
// [START set_messaging_delegate]
Messaging.messaging().delegate = self as? MessagingDelegate
// [END set_messaging_delegate]
//create the notificationCenter
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)
//FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
var token = ""
for i in 0..<deviceToken.count {
token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
}
print("Registration succeeded! Token: ", token)
let topicName = "/topics/ChaclateOnMobile"
Messaging.messaging().subscribe(toTopic: topicName)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Registration failed! \(error)")
}
// Firebase notification received
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (_ options: UNNotificationPresentationOptions) -> Void) {
// custom code to handle push while app is in the foreground
print("Handle push from foreground\(notification.request.content.userInfo)")
let dict = notification.request.content.userInfo["aps"] as! NSDictionary
let d : [String : Any] = dict["alert"] as! [String : Any]
let body : String = d["body"] as! String
let title : String = d["title"] as! String
print("Title:\(title) + body:\(body)")
self.showAlertAppDelegate(title: title,message:body,buttonTitle:"ok",window:self.window!)
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
// if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background
print("Handle push from background or closed\(response.notification.request.content.userInfo)")
}
func showAlertAppDelegate(title: String,message : String,buttonTitle: String,window: UIWindow){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.default, handler: nil))
window.rootViewController?.present(alert, animated: false, completion: nil)
}
// Firebase ended here
}
Check if you are using the correct token for sending notifications.
Have you registered your app to receive Push Notifications?
Check if you have implemented proper methods in AppDelegate.
When the app is not running, the notification is received in didFinishLaunchingWithOptions.
Add this to didFinishLaunchingWithOptions in your code:
if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject]
{
//Your code
}
When your app is in background/foreground, the notification is received in didReceiveRemoteNotification
func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void)
{
//Your code
}

Resources