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.
Related
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()
}
How to handle push notif that it will notify even when the app is open or closed. i have the ff. code below and its notifying when app is close but it does not notify when app is open. i have provided my source code below.Thank You. Help greatly appreciated.How to handle push notif that it will notify even when the app is open or closed. i have the ff. code below and its notifying when app is close but it does not notify when app is open. i have provided my source code below.Thank You. Help greatly appreciated.
import UIKit
import CoreData
import Firebase
import FirebaseMessaging
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
if UserDefaults.standard.bool(forKey: "isLoggedIn") {
let menuVC = storyBoard.instantiateViewController(withIdentifier: "MenuCollectionViewController") as! MenuCollectionViewController
let nvc: UINavigationController = UINavigationController(rootViewController: menuVC)
nvc.navigationBar.isHidden = true
self.window?.rootViewController = nvc
self.window?.makeKeyAndVisible()
} else {
self.showLoginScreen()
}
FirebaseApp.configure()
let notificationTypes : UIUserNotificationType = [UIUserNotificationType.alert , UIUserNotificationType.badge, UIUserNotificationType.sound]
let notificationSettings = UIUserNotificationSettings(types: notificationTypes,categories : nil)
application.registerForRemoteNotifications()
application.registerUserNotificationSettings(notificationSettings)
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// print("MessageID: \(userInfo["gcm_message_id"])")
// print(userInfo)
if let message = userInfo["gcm_message_id"] {
print("MessageID: \(message)")
}
print(userInfo)
}
func showLoginScreen()
{
UserDefaults.standard.set(false, forKey: "isLoggedIn")
UserDefaults.standard.synchronize()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
let nvc: UINavigationController = UINavigationController(rootViewController: loginViewController)
nvc.navigationBar.isHidden = true
self.window?.rootViewController = nvc
self.window?.makeKeyAndVisible()
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "FridgeBoard")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
use below code
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
}
implement below method at app delegate:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(UNNotificationPresentationOptions.alert)
}
Please use this code
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,CLLocationManagerDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
}
#available(iOS 10, *)
// 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(userInfo)
completionHandler([.alert, .badge, .sound])
// Change this to your preferred presentation option
// completionHandler([])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
switch response.actionIdentifier {
case "action1":
print("Action First Tapped")
case "action2":
print("Action Second Tapped")
default:
break
}
// Print full message.
print(userInfo)
Messaging.messaging().appDidReceiveMessage(userInfo)
completionHandler()
}
}
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
I build firebase notification in my app. And it is successful working. But i want to open if notification data is equal "Second" then open SecondViewController in my app. How can i do? I use userInfo but i did not do it.
Firebase Notification Special Data: { "view" : "Second" }
This is my full appdelegate code. Thank you. I am sorry for my english.
import UIKit
import Firebase
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
static var shared: AppDelegate { return UIApplication.shared.delegate as! AppDelegate }
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
application.registerForRemoteNotifications()
requestNotificationAuthorization(application: application)
if let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary {
NSLog("[RemoteNotification] applicationState: \(applicationStateString) didFinishLaunchingWithOptions for iOS9: \(userInfo)")
//TODO: Handle background notification
}
return true
}
var applicationStateString: String {
if UIApplication.shared.applicationState == .active {
return "active"
} else if UIApplication.shared.applicationState == .background {
return "background"
}else {
return "inactive"
}
}
func requestNotificationAuthorization(application: UIApplication) {
if #available(iOS 10.0, *) {
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)
}
}
}
#available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// iOS10+, called when presenting notification in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
NSLog("[UserNotificationCenter] applicationState: \(applicationStateString) willPresentNotification: \(userInfo)")
//TODO: Handle foreground notification
completionHandler([.alert])
}
// iOS10+, called when received response (default open, dismiss or custom action) for a notification
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
NSLog("[UserNotificationCenter] applicationState: \(applicationStateString) didReceiveResponse: \(userInfo)")
//TODO: Handle background notification
completionHandler()
}
}
extension AppDelegate : MessagingDelegate {
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
NSLog("[RemoteNotification] didRefreshRegistrationToken: \(fcmToken)")
}
// iOS9, called when presenting notification in foreground
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
NSLog("[RemoteNotification] applicationState: \(applicationStateString) didReceiveRemoteNotification for iOS9: \(userInfo)")
if UIApplication.shared.applicationState == .active {
//TODO: Handle foreground notification
} else {
//TODO: Handle background notification
}
}
}
notification data from userinfo
inside userNotificationCenter add this code...
let str:String = (userInfo["gcm.notification.imType"] as? String)!
switch str {
case "FIRST":
let rootViewController = self.window!.rootViewController as! UINavigationController
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let firstViewController = storyboard.instantiateViewController(withIdentifier: "FIRSTID") as! MessagesTableViewController
rootViewController.pushViewController(firstViewController, animated: true)
case "SECOND":
let rootViewController = self.window!.rootViewController as! UINavigationController
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondViewController = storyboard.instantiateViewController(withIdentifier: "SECONDID") as! SecondViewController
rootViewController.pushViewController(secondViewController, animated: true)
default:
print("Type is something else")
}