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?
Related
I'm Facing an issue when i Debug Project in Real Device, I'm Getting Notification With Custom Sound, But After making a Build Via Diwai, I'm Not Getting Custom Sound, It Play Default Sound with Notification.I'm Using Firebase. I have Added Custom Sound in Project and added in Bundle Resources as well.
Please Have A look on My Code.
Here's My Code
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate, MessagingDelegate {
var window: UIWindow?
var audioPlayer : AVAudioPlayer?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let content = UNMutableNotificationContent()
content.sound = UNNotificationSound.default
content.sound = UNNotificationSound(named:UNNotificationSoundName(rawValue: "Eigenintro.aiff"))
FirebaseApp.configure()
let audioSessionError: Error? = nil
do {
try AVAudioSession.sharedInstance().setCategory(.playback, options: .mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)
} catch let audioSessionError {
print(audioSessionError.localizedDescription)
}
UIApplication.shared.beginReceivingRemoteControlEvents()
if let audioSessionError = audioSessionError {
print("[AppDelegate] audioSessionError: \(audioSessionError)")
}
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().isAutoInitEnabled = true
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: { [self] _, _ in
Messaging.messaging().delegate = self
}
)
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching FCM registration token: \(error)")
} else if let token = token {
print("FCM registration token: \(token)")
}
}
application.registerForRemoteNotifications()
return true
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase registration token: \(String(describing: fcmToken))")
self.sendDataToServer(token: fcmToken!)
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions)
-> Void) {
let userInfo = notification.request.content.userInfo
defer {
completionHandler([.badge,.sound, .alert])
SoundPlayer.sharedInstance.playSound()
}
print(#function)
print(userInfo)
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
print(#function)
print(userInfo)
completionHandler()
}
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.hexString
print("APNs Device Token: \(token)")
#if DEVELOPMENT
Messaging.messaging().apnsToken = deviceToken
#else
Messaging.messaging().setAPNSToken(deviceToken, type: .prod)
#endif
}
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print(#function)
Messaging.messaging().appDidReceiveMessage(userInfo)
if application.applicationState == .background {
guard let soundURL = Bundle.main.url(forResource: "Eigenintro", withExtension: "aiff") else { return }
//let soundUrl = URL(fileURLWithPath: path)
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
print("[AppDelegate] audioPlayer play call")
audioPlayer!.play()
} catch let audioPlayerError {
print("[AppDelegate] audioPlayerError: \(audioPlayerError)")
}
completionHandler(UIBackgroundFetchResult.newData)
} else {
completionHandler(UIBackgroundFetchResult.noData)
}
}
// foreground
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print("didReceiveRemoteNotification: Received new push Notification")
Messaging.messaging().appDidReceiveMessage(userInfo)
print(#function)
print("didReceiveRemoteNotification: Push notificationMessage is: \(userInfo)")
}
}
My FCM Payload
{
"message": {
"token": "fcm token",
"notification": {
"title": "Breaking News",
"body": "New news story available."
},
"apns": {
"payload": {
"aps": {
"category" : "NEW_MESSAGE_CATEGORY",
"sound": "Eigenintro.aiff"
}
}
}
}
}
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 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]
}
}
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 do like below in Swift 2. But It's not working in Swift 3. How Can I provide this? If someone explain this It would be great.
didFinishLaunchingWithOptions
let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
application.registerForRemoteNotifications()
and
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != .None {
application.registerForRemoteNotifications()
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
print("Meesage ID \(userInfo["gcm_message_id"]!)")
print(userInfo)
}
I can do simple local notification but, I couldn't remote push notification from Firebase.
I tried
UNUserNotificationCenter.currentNotificationCenter().delegate = self
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Alert, .Badge, .Sound]) { (success, error:NSError?) in
if success {
print("Notification access true!")
application.registerForRemoteNotifications()
}
else {
print(error?.localizedDescription)
}
}
and
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
print("Meesage ID \(userInfo["gcm_message_id"]!)")
print(userInfo)
}
still doesn't work.
The AppDelegate method names have changed a little and UserNotifications framework has been introduced. You must use this framework for notifications in iOS 10 and above as the other methods are being deprecated.
import UserNotifications
...
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
...
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> ()) {
print("Message ID \(userInfo["gcm.message_id"]!)")
print(userInfo)
}
...
}
Registering for Push Notifications in Xcode 8/Swift 3.0?
It is very important to remember that there may be different devices that run different versions of the iOS, and they may have different notification capabilities. I understand that the previous answer does point in the right direction.
We need to import FirebaseInstanceID, if we are to receive instance, or event based notifications. Such notifications are like the ones that pop-up when someone retweets our post, or likes a post, or a message notification.
However, if someone is looking for the complete code that goes into the didFinishLaunchingWithOptions function in AppDelegate, here it is:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
FIRApp.configure()
if #available(iOS 10.0, *) {
let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound]
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
authOptions, completionHandler: {_,_ in })
} else {
// Fallback on earlier versions
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
application.registerForRemoteNotifications()
// Add observer for InstanceID token refresh callback.
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: kFIRInstanceIDTokenRefreshNotification,
object: nil)
return true
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// This is required if you are receiving a notification message while your app is in the background, which is the most common case!!
print("Message ID: \(userInfo["gcm.message_id"]!)")
print("%#", userInfo)
}
func tokenRefreshNotification(notification: NSNotification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
}
connectToFcm()
}
func connectToFcm() {
FIRMessaging.messaging().connectWithCompletion { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
func applicationDidBecomeActive(application: UIApplication) {
connectToFcm()
}
func applicationDidEnterBackground(application: UIApplication) {
FIRMessaging.messaging().disconnect()
print("Disconnected from FCM.")
}
This is what works for me Xcode 8, Swift 3.
Inside didFinishLaunchingwithOptions func in AppDelegate.swift
if #available(iOS 10.0, *) {
let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {granted, error in
print(granted)
})
// 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)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
FIRApp.configure()
// [START set_messaging_delegate]
FIRMessaging.messaging().remoteMessageDelegate = self
// [END set_messaging_delegate]
And the Delegates required to receive notifications from firebase:
#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.
print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print("%#", userInfo)
let aps = userInfo["aps"] as! [String: Any]
let notificationMessage = aps["alert"] as! String // processed content from notificaton
}
}
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print("%#", remoteMessage.appData)
}
}