Swift - Firebase 4 - Proper method to handle remoteMessage - ios

Everything was working good in Firebase v3.
I recently upgraded to Firebase v4.
I implemented all the protocol functions.
Stil Received msg is not handled and I get below warning
[Firebase/Messaging][I-FCM002019] FIRMessaging received data-message, but FIRMessagingDelegate's-messaging:didReceiveMessage: not implemented
func application(appPsgVar: UIApplication,
didReceiveRemoteNotification userInfo: [NSObject : AnyObject])
{
let remoteMessage = userInfo
print("Forground : remoteMessage : \(remoteMessage)")
Messaging.messaging().appDidReceiveMessage(remoteMessage)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)
{
let remoteMessage = userInfo
print("Background : remoteMessage : \(remoteMessage)")
Messaging.messaging().appDidReceiveMessage(remoteMessage)
completionHandler(UIBackgroundFetchResult.NewData)
}
// Fcm Message Received Handler Functions :
func application(received remoteMessage: MessagingRemoteMessage)
{
// What message comes here?
print("remoteMessage.appData : ", remoteMessage.appData)
}
// older way
func application(remoteMessage: MessagingRemoteMessage)
{
print("remoteMessage.appData : ", remoteMessage.appData)
}
// Fcm Message protocol Functions :
func messaging(messaging: Messaging, didRefreshRegistrationToken fcmToken: String)
{
print("New FCM Token received : \(fcmToken)")
}
#available(iOS 10.0, *)
func messaging(messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage)
{
// What message comes here ?
print("remoteMessage.appData : ", remoteMessage.appData)
}
|*| If I try to implement this method its says :
func applicationReceivedRemoteMessage(remoteMessage: MessagingRemoteMessage)
{
print("%#", remoteMessage.appData)
}
Objective-C method 'applicationReceivedRemoteMessage:' provided by method 'applicationReceivedRemoteMessage' conflicts with optional requirement method 'application(received:)' in protocol 'MessagingDelegate'
Kindly let me know which is the new correct method

Related

PhoneAuthProvider just started throwing error (possibly on simulator only)

Out of nowhere, the PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) started failing on my simulator, but still works on my device (same build obviously). I've tried both real phone numbers and testing phone numbers.
I'm on SDK version 9.6.0 and run it on an iOS 16.1 simulator.
Here's the error I'm getting:
Error Domain=FIRAuthErrorDomain Code=17048 "Token mismatch" UserInfo={NSLocalizedDescription=Token mismatch, FIRAuthErrorUserInfoNameKey=INVALID_APP_CREDENTIAL}
Here's my AppDelegate:
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void
) {
let userInfo = response.notification.request.content.userInfo
completionHandler()
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Auth.auth().setAPNSToken(deviceToken, type: .unknown)
Messaging.messaging().apnsToken = deviceToken
}
func application(_ application: UIApplication, didReceiveRemoteNotification notification: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
Messaging.messaging().appDidReceiveMessage(notification)
if (Auth.auth().canHandleNotification(notification)) {
completionHandler(.noData)
return
}
}
}
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
let tokenDict = ["token": fcmToken ?? ""]
NotificationCenter.default.post(
name: Notification.Name("FCMToken"),
object: nil,
userInfo: tokenDict)
}
}
Also here’s my Firebase certificates setup:
Any ideas?
EDIT: Now that I think about it, yesterday I updated my macOS to 13.0.1. Could it have anything to do with it?
EDIT 2: It seems that it still works on an iOS 15 simulator
I had the same issue, I finally nailed it : I updated Firebase to the latest version (10.2) and now it works on iOS 16 too :-)

App delegate methods not triggered on receipt of firebase notifications in iOS, but display in banner on screen

I've implemented FCM push notifications for my iOS app such that when a notification is delivered a banner with the expected payload is displayed on my iPhone screen, but none of my App Delegate methods are invoked.
My implementation closely follows the firebase cloud messaging documentation here with method swizzling disabled.
Why don't my app delegate methods trigger when I receive a push notification?
How can I execute code on receipt of a remote notification?
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().delegate = self
return true
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
/* Invoked when a notification arrives when the app is running in the foreground. */
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler:
#escaping (UNNotificationPresentationOptions) -> Void
) {
let userInfo = notification.request.content.userInfo
Messaging.messaging().appDidReceiveMessage(userInfo)
completionHandler([[.banner, .sound, .badge]])
}
/* Invoked when notification arrives when the app is running in the background. */
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void
) {
let userInfo = response.notification.request.content.userInfo
Messaging.messaging().appDidReceiveMessage(userInfo)
completionHandler()
}
/** Method swizzling disabled requirement. */
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
Messaging.messaging().apnsToken = deviceToken
}
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
Messaging.messaging().appDidReceiveMessage(userInfo)
completionHandler(.noData)
}
}
extension AppDelegate: MessagingDelegate {
func messaging(
_ messaging: Messaging,
didReceiveRegistrationToken fcmToken: String?
) {
let tokenDict = ["token": fcmToken ?? ""]
NotificationCenter.default.post(
name: Notification.Name("FCMToken"),
object: nil,
userInfo: tokenDict
)
writeFCMTokenToFirestore(token: fcmToken)
}
}
On the backend I am using the firebase admin SDK within a Cloud Function to send notifications with a custom payload, as below.
const admin = require('firebase-admin');
const token = getDeviceToken();
const payload = {
notification: {
title: 'test',
badge: '1'
}
}
admin.messaging().sendToDevice(token, payload)
.then((response) => {
// Success
})
.catch((error) => {
// Failure
});

FCM token don't call didReceiveRegistrationToken

Hi using FCM into my application.
When I am trying to read FCM token even compiler don't call this delegate method also is any way please help.
when I put breaks and check this method is don't call I using ios11 swift4
extension AppDelegate: MessagingDelegate{
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Message data:", remoteMessage.appData)
}
}
didReceiveRegistrationToken
is a delegate function. it will get called upon receiving token form firebase. if it's not getting called make sure you've following code in AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
return true
}
with Messaging.messaging().delegate = self we are registering AppDelegate for receiving the method call from Firebase
I using the following function it is working fine
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
if let refreshedToken = InstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
}
}

FCM Push notification not working in iOS 11

I need to handle push notification and that's done with a lower version of ios but in ios 11 never receive any push notification. I using Firebase Cloud Messaging. please, anyone has a solution then please share.
Please Check as
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Use Firebase library to configure APIs
FirebaseApp.configure()
self.registerForPushNotifications(application: application)
Messaging.messaging().delegate = self
if let token = InstanceID.instanceID().token() {
NSLog("FCM TOKEN : \(token)")
DataModel.sharedInstance.onSetUserFCMStringToken(FCM: token)
self.connectToFcm()
}
if launchOptions != nil {
//opened from a push notification when the app is closed
_ = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] ?? [AnyHashable: Any]()
}
else {
//opened app without a push notification.
}
return true
}
#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] 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] didReceiveResponse: \(userInfo)")
//TODO: Handle background notification
completionHandler()
}}
extension AppDelegate : MessagingDelegate {
//MARK: FCM Token Refreshed
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
NSLog("[RemoteNotification] didRefreshRegistrationToken: \(fcmToken)")
}
// Receive data message on iOS 10 devices while app is in the foreground.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
NSLog("remoteMessage: \(remoteMessage.appData)")
}}
//Register for push notification.
func registerForPushNotifications(application: UIApplication) {
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert,.sound]) { (granted, error) in
if error == nil{
DispatchQueue.main.async(execute: {
application.registerForRemoteNotifications()
})
}
}
}
else {
let settings = UIUserNotificationSettings(types: [.alert,.sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
// Add observer for InstanceID token refresh callback.
NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)
}
#objc func tokenRefreshNotification(_ notification: Notification) {
print(#function)
if let refreshedToken = InstanceID.instanceID().token() {
NSLog("Notification: refresh token from FCM -> \(refreshedToken)")
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
func connectToFcm() {
// Won't connect since there is no token
guard InstanceID.instanceID().token() != nil else {
NSLog("FCM: Token does not exist.")
return
}
Messaging.messaging().shouldEstablishDirectChannel = true
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NSLog("Notification: Unable to register for remote notifications: \(error.localizedDescription)")
}
// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to the InstanceID token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
// iOS9, called when presenting notification in foreground
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
NSLog("didReceiveRemoteNotification for iOS9: \(userInfo)")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
}
Problem seems to be with
FirebaseInstanceID Version less than 1.0.9
FirebaseInstanceID Version between 2.0.1 - 2.0.3
Set your pod file as below :
For Swift 2.3 and Xcode 8 : (FirebaseInstanceID v1.1.0 gets installed)
pod 'Firebase/Core', '3.8.0'
pod 'Firebase/Messaging'
For Swift 3 and Xcode 9 :
pod 'Firebase/Core'
pod 'Firebase/Messaging'
pod 'FirebaseInstanceID', "2.0.0
I didn't want to upgrade to FirebaseInstanceID 2.0.0 to fix the issue as I wanted use Swift 2.3 only
I had the same problem, the issue was I was missing my APN configuration in firebase console.

Swift - Firebase - applicationReceivedRemoteMessage Conflict

Using Swift 2.3 - Firebase 4
|*| If I try to implement this method its says :
func applicationReceivedRemoteMessage(remoteMessage: MessagingRemoteMessage)
{
print("%#", remoteMessage.appData)
}
Objective-C method 'applicationReceivedRemoteMessage:' provided by method 'applicationReceivedRemoteMessage' conflicts with optional requirement method 'application(received:)' in protocol 'MessagingDelegate'
Kindly let me know which is the new correct method
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
}
reference: https://firebase.google.com/docs/cloud-messaging/ios/receive
Implement following delegate methods in your AppDelegate.swift file:
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Remote message received for this app")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print("This \(userInfo)")
Messaging.messaging().appDidReceiveMessage(userInfo)
}

Resources