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
Related
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.
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 :)
In order to try out Push Notifications with Firebase I have been following these three documents:
One, Two, Three and Four.
I have one question, but before asking; here is what I can see:
When my app is in the foreground and a notification is sent, only this function is called:
userNotificationCenter(_:willPresent:withCompletionHandler:)
If I tap on the notification, then this one is also so called:
userNotificationCenter(_:didReceive:withCompletionHandler:)
When my app is in the background and a notification is sent, nothing is called.
If I tap on the notification, then this one is called:
userNotificationCenter(_:didReceive:withCompletionHandler:)
As a result of this situation, whithout having to react (by tapping on the notification); I can have the app perform some useful action when a notification is arriving while in the foreground, using the userNotificationCenter(_:willPresent:withCompletionHandler:) function.
On the other hand while in the background, I can only have the app perform some useful action when a notification is arriving if the user taps on the notification.
Is there a way for me to also have the app perform some useful action even if the user has no reaction?
Here is the relevant code I have at this point:
import UIKit
import Firebase
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {
granted, error in
if error != nil {print("Error: \(error!)")}
if granted {
DispatchQueue.main.async
{application.registerForRemoteNotifications()}
}
})
FirebaseApp.configure()
.......
return true
}
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print(#function)
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print(#function)
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
}
For information, I am using Xcode Version 10.1, iOS 12.1 and Swift 4.2.
swift 4.2, Xcode 10.0, IOS 12.0
import UIKit
import Firebase
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.badge, .alert , .sound]) { (granted, error) in
let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
let setting = UIUserNotificationSettings(types: type, categories: nil)
UIApplication.shared.registerUserNotificationSettings(setting)
UIApplication.shared.registerForRemoteNotifications()
}
} else {
let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
let setting = UIUserNotificationSettings(types: type, categories: nil)
UIApplication.shared.registerUserNotificationSettings(setting)
UIApplication.shared.registerForRemoteNotifications()
}
application.registerForRemoteNotifications()
if(FIRApp.defaultApp() == nil){
FIRApp.configure()
}
NotificationCenter.default.addObserver(self,
selector: #selector(self.tokenRefreshNotification(notification:)),
name: NSNotification.Name.firInstanceIDTokenRefresh,
object: nil)
return true
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo as? NSDictionary
_ = UIStoryboard(name: "Main", bundle: nil)
let appdelegate = UIApplication.shared.delegate as! AppDelegate
let aps = userInfo?["aps"] as! NSDictionary
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Convert token to string
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("Device Token", deviceTokenString)
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)
}
func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
let appdelegate = UIApplication.shared.delegate as! AppDelegate
let aps = data["aps"] as! NSDictionary
let state = UIApplication.shared.applicationState
if state == .background {
}
if state == .active {
}
}
//MARK: Notification Center Call
func callNotificationCenter(){
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadData"), object: nil)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
}
// start firebase
#objc func tokenRefreshNotification(notification: NSNotification) {
let refreshedToken = FIRInstanceID.instanceID().token()
print(refreshedToken)
connectToFcm()
}
func connectToFcm() {
FIRMessaging.messaging().connect { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(error?.localizedDescription ?? "")")
} else {
print("Connected to FCM")
}
}
}
How to open a Application when app is in killed/closed state , i m getting the notifications but when i click on notification app is not opening,, but working fine when app in foreground or background.I tried below code still not getting where is issue.Pls check what i have tried
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(grant, error) in
if error == nil {
if grant {
DispatchQueue.main.async(execute: {
application.registerForRemoteNotifications()
})
} else {
//User didn't grant permission
}
} else {
print("error: ",error as Any)
}
})
} else {
// Fallback on earlier versions
let notificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(notificationSettings)
}
self.updateAppPNBadge()
if let notification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [String : AnyObject] {
_ = notification["aps"] as! [String : AnyObject]
(window?.rootViewController as! TabBar).selectedIndex = 4
}
return true
}
func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != .none {
application.registerForRemoteNotifications()
}
}
// Token registered
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenString = deviceToken.reduce("") { string, byte in
string + String(format: "%02X", byte)
}
print("token: ", tokenString)
UserDefaults.standard.set("\(tokenString)", forKey: "tokenID")
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void)
{
completionHandler([UNNotificationPresentationOptions.alert,UNNotificationPresentationOptions.sound,UNNotificationPresentationOptions.badge])
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
if #available(iOS 10.0, *) {
if let info = userInfo["aps"] as? Dictionary<String, AnyObject>
{
print("\(info)")
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "TabBar") as! UITabBarController
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = vc
vc.selectedIndex = 4
self.window?.makeKeyAndVisible()
}
}
else {
if let info = userInfo["aps"] as? Dictionary<String, AnyObject>
{
let alertMsg = info["alert"] as? String
let alert = UIAlertView(title: "", message: alertMsg, delegate: nil, cancelButtonTitle: "OK")
alert.show()
print("\(info)")
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "TabBar") as! UITabBarController
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = vc
vc.selectedIndex = 4
self.window?.makeKeyAndVisible()
}
}
UIApplication.shared.applicationIconBadgeNumber = UIApplication.shared.applicationIconBadgeNumber + 1
}
func updateAppPNBadge() {
UIApplication.shared.applicationIconBadgeNumber = 0
UIApplication.shared.cancelAllLocalNotifications()
}
func applicationWillResignActive(_ application: UIApplication) {
self.updateAppPNBadge()
}
func applicationDidEnterBackground(_ application: UIApplication) {
self.updateAppPNBadge()
}
func applicationWillTerminate(_ application: UIApplication) {
self.updateAppPNBadge()
}
I have successfully added firebase and notification in my project. Using this Notifications are coming and I can access them by tapping on that notification. But the issue is if my app is closed, I got a notification, now without tapping on that I cleared that. Now no data inserted in my Db. How to keep all notifications on queue to access directly when app is opened next time. Thanks in advance.
class AppDelegate: UIResponder, UIApplicationDelegate , CLLocationManagerDelegate , FIRMessagingDelegate , UNUserNotificationCenterDelegate {
var window: UIWindow?
var locationManager = CLLocationManager()
var utill = FencingUtil()
var wrap = WrapperApi()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if launchOptions != nil{
let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification]
if userInfo != nil {
self.handleUserInfo(userinfo: userInfo as! [AnyHashable : Any])
// Perform action here
}
}
self.locationManager.delegate = self
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.distanceFilter = 50.0; // Will notify the LocationManager every 100 meters
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
GMSServices.provideAPIKey("AIzaSyDNoFY_sbP9j-ObZx06B_rmjcCVrCM_ZP0")
GMSPlacesClient.provideAPIKey("AIzaSyDNoFY_sbP9j-ObZx06B_rmjcCVrCM_ZP0")
FIRApp.configure()
// var db: SQLiteDatabase
let dataStore = SQLiteDataStore.sharedInstance
do {
try dataStore.createTables()
}
catch _{}
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(grant, error) in
if error == nil {
if grant {
application.registerForRemoteNotifications()
} else {
//User didn't grant permission
}
} else {
print("error: ",error)
}
})
// For iOS 10 display notification (sent via APNS)
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
print("Handle push from foreground")
// custom code to handle push while app is in the foreground
//print("\(notification.request.content.userInfo)")
self.handleUserInfo(userinfo: notification.request.content.userInfo)
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
print("Handle push from background or closed")
// if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background
self.handleUserInfo(userinfo: response.notification.request.content.userInfo)
}
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage)
{
print("%#", remoteMessage.appData)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any])
{ self.application(application, didReceiveRemoteNotification: userInfo) { (UIBackgroundFetchResult) in }
print ("dasdasd")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
self.handleUserInfo(userinfo: userInfo)
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.prod)
}
func tokenRefreshNotificaiton(_ notification: Foundation.Notification) {
guard let refreshedToken = FIRInstanceID.instanceID().token()
else {
return
}
//refreshedToken = FIRInstanceID.instanceID().token()!
print("InstanceID token: \(refreshedToken)")
utill.tokenDefault.setValue(refreshedToken, forKey: "tokenId")
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
// [START connect_to_fcm]
func connectToFcm() {
FIRMessaging.messaging().connect { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(String(describing: error))")
} else {
//print("Connected to FCM.")
}
}
}}
if you are launching your application then you can get you notification object in didFinishLaunchingWithOptions method try this. if you have
not cleared notification from notification center.
if (launchOptions != nil) {
if let remoteNotification = launchOptions?
[UIApplicationLaunchOptionsKey.remoteNotification] {
let objNotification = remoteNotification as! [AnyHashable :
Any]
}
}