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]
}
}
Related
I am trying to put iOS push notifications onto my app. But keep getting the error
The object <FancyDeliveryManager.ViewController: 0x101910170> does not respond to -messaging:didReceiveRegistrationToken:. Please implement -messaging:didReceiveRegistrationToken: to be provided with an FCM token.
My app delegate looks like:
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
var window : UIWindow?
//private let pushNotificationHandler: PushNotificationHandler = PushNotificationHandler()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
//notification delegates
Messaging.messaging().delegate = self //enables recievieving of tokens
UNUserNotificationCenter.current().delegate = self
///
//set up nav controller
let root: UIViewController = ViewController()
let navigationController = UINavigationController(rootViewController: root)
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
return true
}
//MARK: Push Handling
func registerForPushNotifications() {
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge]) {
[weak self] granted, error in
guard granted else { return }
self?.getNotificationSettings()
}
}
//check the notification settings
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
// 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])
}
//called when user interacts with push notification
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
print("Launched from push notification")
completionHandler()
}
// This callback is fired at each app startup and whenever a new token is created.
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
saveFcmToken(token: fcmToken)
}
//save token in database
func saveFcmToken(token: String){
var ref: DatabaseReference!
ref = Database.database().reference()
guard let userID = Auth.currentUser else { return }
ref.child("WarehouseManagers/\(userID)/fcmToken").setValue(token)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
//default to delegate method below
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
// With swizzling disabled you must set the APNs token here.
// Messaging.messaging().apnsToken = deviceToken
}
func applicationDidBecomeActive(_ application: UIApplication) {
UIApplication.shared.applicationIconBadgeNumber = 0
}
Is there something in the main ViewController that needs to be added here?
Any help would be greatly appreciated.
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?
I have an issue, and can't figure out what is the problem. I have integrated Firebase in my app. Everything was OK until I updated to xCode 8.3 and Swift3.1.
I receive the notification in Foreground in the console from the FCM but when I enter in Background or even in Foreground
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void)
is never executed and I'm not able to handle the notification
This is what I am receiving from the FCM
[AnyHashable("from"): 1234456, AnyHashable("sender_name"): Driver, AnyHashable("type"): NEW_MESSAGE, AnyHashable("text"): text ;)]
In AppDelegate I have the following:
import UIKit
import CoreData
import FBSDKCoreKit
import FBSDKLoginKit
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
var apiManagerFunc = ApiManager()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
// For iOS 10 data message (sent via FCM)
FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
application.registerForRemoteNotifications()
if let options: NSDictionary = launchOptions as NSDictionary? {
let remoteNotification = options[UIApplicationLaunchOptionsKey.remoteNotification]
if let notification = remoteNotification {
self.application(application, didReceiveRemoteNotification: notification as! [AnyHashable: Any], fetchCompletionHandler: { (result) in
})
}
}
// [START add_token_refresh_observer]
// Add observer for InstanceID token refresh callback.
NotificationCenter.default.addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: .firInstanceIDTokenRefresh,
object: nil)
// [END add_token_refresh_observer]
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
connectToFcm()
}
return true
}
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
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// Let FCM know about the message for analytics etc.
FIRMessaging.messaging().appDidReceiveMessage(userInfo)
// handle your message
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
if application.applicationState == .active {
let userInfoCheck = userInfo["type"] as! String
if userInfoCheck == "LOCATION_REQUEST" {
let valueCheck = UserDefaults.standard.value(forKey: "myLocationSwitchState") as! String
if valueCheck == "on" {
self.showAlertAppDelegate(title: "", message: userInfo["text"] as! String, buttonTitle: "Ok", window: self.window!)
self.updateLocationToServer()
print("Shown")
} else {
print(valueCheck)
}
} else {
self.showAlertAppDelegate(title: "New Message", message: userInfo["text"] as! String, buttonTitle: "Ok", window: self.window!)
}
} else {
let userInfoCheck = userInfo["type"] as! String
if userInfoCheck == "LOCATION_REQUEST" {
let valueCheck = UserDefaults.standard.value(forKey: "myLocationSwitchState") as! String
if valueCheck == "on" {
scheduleLocalNotification(message: userInfo["text"] as! String)
print("Shown")
self.updateLocationToServer()
} else {
print(valueCheck)
}
} else {
scheduleLocalNotification(message: userInfo["text"] as! String)
}
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
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: true, completion: nil)
}
func scheduleLocalNotification(message: String) {
// create a corresponding local notification
let notification = UILocalNotification()
notification.alertBody = message
// play default sound
notification.soundName = UILocalNotificationDefaultSoundName
// assign a unique identifier to the notification so that we can retrieve it later
notification.userInfo = ["UUID": UUID().uuidString]
notification.category = "XXXXXXXXXXXXXXX"
UIApplication.shared.scheduleLocalNotification(notification)
}
func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
print(notification)
}
// [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 {
print("Unable to connect with FCM. \(String(describing: error))")
} else {
print("Connected to FCM.")
}
}
}
// [END connect_to_fcm]
// Successful registration and you have a token. Send the token to your provider, in this case the console for cut and paste.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
print("Successful registration. Token is:")
print(tokenString(deviceToken))
}
// Failed registration. Explain why.
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register for remote notifications: \(error.localizedDescription)")
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
FIRMessaging.messaging().disconnect()
print("Disconnected from FCM.")
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
connectToFcm()
FBSDKAppEvents.activateApp()
FIRMessaging.messaging().connect { error in
print(error as Any)
}
}
#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
// 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(.badge)
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler()
}
}
// [END ios_10_message_handling]
// [START ios_10_data_message_handling]
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices while app is in the foreground.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print(remoteMessage.appData)
}
}
// [END ios_10_data_message_handling]
There is no error behind this. Its just that this method will not get called unless you tap on the notification.
I am working with iOS Swift Notifications Module. I'm not getting the Alert/Banner Notification on the device.
I’m able to get notification when the App is open i.e. in Foreground, but not when app in in Background or Terminated.
Following is my code
import UIKit
import UserNotifications
import Firebase
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate {
var window: UIWindow?
// MARK: - Application Life Cycle
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FIRApp.configure()
askNotificationPermission(application)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.getFirebaseInstaceID(_:)), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
connectToFcm()
return true
}
// MARK:- Push Notification Delegate Methods
#nonobjc func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print(error)
}
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
let appdata = remoteMessage.appData as NSDictionary as! [String: AnyObject]
print(appdata)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// Receive displayed notifications for iOS 10 devices.
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
print("Message ID: \(userInfo["gcm.message_id"]!)")
print("%#", userInfo)
}
// MARK: - Permissions
func askNotificationPermission(_ application: UIApplication) {
if #available(iOS 10.0, *) {
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { (finished, error) in
})
UNUserNotificationCenter.current().delegate = self
FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
}
// MARK: - Firebase Connection Methods
#objc func getFirebaseInstaceID(_ notification: Notification) {
if isNotNull(FIRInstanceID.instanceID().token() as AnyObject?) {
let strFirebaseInstanceID = FIRInstanceID.instanceID().token()! as String
if !strFirebaseInstanceID.isEmpty {
print("Firebase Instance ID - \(strFirebaseInstanceID)")
setString(strValue: strFirebaseInstanceID, forKey: Default.firebaseInstanceID)
NotificationCenter.default.post(name: Notification.Name(rawValue: Notifications.nSendFirebaseID), object: nil)
} else {
setString(strValue: "", forKey: Default.firebaseInstanceID)
}
} else {
setString(strValue: "", forKey: Default.firebaseInstanceID)
}
connectToFcm()
}
func connectToFcm() {
FIRMessaging.messaging().connect { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
}
For iOS 10.*, you need to give push notification present option in completion handler of willPresent notification method list below. Try like this may be helpful.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
Thanks.
As you are sending push using FCM, try sending this payload to FCM for push.
{
"to": "<REGISTRATION_TOKEN_HERE>",
"notification": {
"body": "Yipeee!!! I nailed it",
"sound" : "default"
},
"data" : ""
}
I forgot to add this method
didReceiveRemoteNotification
I am working with Xcode 8.1 & swift 2.3 here I am using firebase integration for getting push notifications.I don't know why i am not getting notifications..
My code:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if #available(iOS 10.0, *) {
let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound]
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
authOptions,
completionHandler: {_,_ in })
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.currentNotificationCenter().delegate = self
// For iOS 10 data message (sent via FCM)
FIRMessaging.messaging().remoteMessageDelegate = self
application.registerForRemoteNotifications()
} else
{
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
FIRApp.configure()
// Add observer for InstanceID token refresh callback.
if #available(iOS 10.0, *) {
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: kFIRInstanceIDTokenRefreshNotification,
object: nil)
} else {
// Fallback on earlier versions
}
return true
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
FIRMessaging.messaging().appDidReceiveMessage(userInfo)
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings)
{
application.registerForRemoteNotifications()
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
print(deviceToken)
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for i in 0..<deviceToken.length {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
//Tricky line
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)
print("Device Token:", tokenString)
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
// Print the error to console (you should alert the user that registration failed)
print("APNs registration failed: \(error)")
}
#available(iOS 10.0, *)
func tokenRefreshNotification(notification: UNUserNotificationCenter) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
let deviceFCMToken: String = refreshedToken
NSUserDefaults.standardUserDefaults().setObject(deviceFCMToken, forKey: "FCMToken")
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isFCMTokenAvailable")
//UIApplication.sharedApplication().registerForRemoteNotifications()
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
func connectToFcm()
{
FIRMessaging.messaging().connectWithCompletion { (error) in
if (error != nil)
{
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
extension AppDelegate : FIRMessagingDelegate
{
// Receive data message on iOS 10 devices.
func applicationReceivedRemoteMessage(remoteMessage: FIRMessagingRemoteMessage)
{
print("%#", remoteMessage.appData)
}
}
Since you requested me on another thread's comment section, I am posting this working set of code with the same configuration you have mentioned:
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,CLLocationManagerDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//############## FIREBASE ##################
registerForPushNotifications(application)
FIRApp.configure()
// Add observer for InstanceID token refresh callback.
NSNotificationCenter
.defaultCenter()
.addObserver(self, selector: #selector(AppDelegate.tokenRefreshNotification),
name: kFIRInstanceIDTokenRefreshNotification, object: nil)
//############ FIREBASE END ################
return true
}
//MARK: - FIREBASE START
//######################################## FIREBASE START ###########################################
func registerForPushNotifications(application: UIApplication) {
if #available(iOS 10.0, *){
UNUserNotificationCenter.currentNotificationCenter().delegate = self
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert], completionHandler: {(granted, error) in
if (granted)
{
UIApplication.sharedApplication().registerForRemoteNotifications()
}
else{
//Do stuff if unsuccessful...
}
})
}
else{ //If user is not on iOS 10 use the old methods we've been using
let notificationSettings = UIUserNotificationSettings(
forTypes: [.Badge, .Sound, .Alert], categories: nil)
application.registerUserNotificationSettings(notificationSettings)
}
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != .None {
application.registerForRemoteNotifications()
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for i in 0..<deviceToken.length {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
//Tricky line
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
print("Device Token:", tokenString)
print("Firebase Token:",FIRInstanceID.instanceID().token())
}
// [START receive_message]
#available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
//Handle the notification
//Use this place to handle
}
#available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
//Handle the notification
//Use this place to handle the notification
print(response)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print(userInfo)
}
// [END receive_message]
// [START refresh_token]
func tokenRefreshNotification(notification: NSNotification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
// [END refresh_token]
// [START connect_to_fcm]
func connectToFcm() {
FIRMessaging.messaging().connectWithCompletion { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
// [END connect_to_fcm]
func applicationDidBecomeActive(application: UIApplication) {
connectToFcm()
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
//FBSDKAppEvents.activateApp()
}
// [START disconnect_from_fcm]
func applicationDidEnterBackground(application: UIApplication) {
//FIRMessaging.messaging().disconnect()
print("Disconnected from FCM.")
}
// [END disconnect_from_fcm]
//###################################### FIREBASE ##########################################
//######################################## END #############################################
}
Payload Format:
[aps: {
alert = {
body = "Some message.";
title = "Some title";
};
category = " ";
}, Name: ios, gcm.message_id: 0:1474608925388897%17bce75117bc5555]
#Uma Madhavi
Try adding below method
SWIFT
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.alert)
}
Objective-C
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
completionHandler(UNNotificationPresentationOptionAlert);
}