everyone!
Please I am facing some challenges integrating Firebase Messaging for Push Notifications on Xcode in SwiftUI.
I installed the SDK and all, got the APN from App Store Connect and made a new project in Firebase. I added the Google Info file to my Project. I tested it and it seemed to work with the Test option in Firebase Messaging Notifications. I could even get it when my phone was not connected to the laptop.
But, after distributing to App Store, the notifications did not work.
Frustrated, I deleted the App from Firebase and got a new Key APN from App Store Connect and revoked the old one, and tried different codes of integration into the app.
They give me the Token to test with proving it was installed, but now, even the Test Notification is not working. I have removed the Firebase, done the clean build and everything, disabled Firebase Proxy and all, double checked the bundle ID…
But, it is not functioning at all.
Can someone kindly help me out?
The first code was:
import SwiftUI
import SwiftData
import Firebase
import UserNotifications
@main
struct AppNameApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var sharedModelContainer: ModelContainer = {
let schema = Schema([
Item.self,
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
return try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: (error)")
}
}()
//Network Monitor
@StateObject var networkMonitor = NetworkMonitor()
//BODY
var body: some Scene {
WindowGroup {
ContentView()
.environment(.font, Font.custom("Avenir Next", size: 14))
.environmentObject(networkMonitor)
}
.modelContainer(sharedModelContainer)
}
}
//Firebase
class AppDelegate: NSObject, UIApplicationDelegate {
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: (messageID)")
}
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
}
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
let deviceToken:[String: String] = ["token": fcmToken ?? ""]
print("Device token: ", deviceToken) // This token can be used for testing notifications on FCM
}
}
@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
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: (messageID)")
}
print(userInfo)
// Change this to your preferred presentation option
completionHandler([[.banner, .badge, .sound]])
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID from userNotificationCenter didReceive: (messageID)")
}
print(userInfo)
completionHandler()
}
}
And the second I have tried is:
import SwiftUI
import SwiftData
import Firebase
import UserNotifications
import FirebaseCore
@main
struct AppNameApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var sharedModelContainer: ModelContainer = {
let schema = Schema([
Item.self,
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
return try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: (error)")
}
}()
//Network Monitor
@StateObject var networkMonitor = NetworkMonitor()
//BODY
var body: some Scene {
WindowGroup {
ContentView()
.environment(.font, Font.custom("Avenir Next", size: 14))
.environmentObject(networkMonitor)
}
.modelContainer(sharedModelContainer)
}
}
class AppDelegate: NSObject, UIApplicationDelegate {
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: (messageID)")
}
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
}
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
let deviceToken:[String: String] = ["token": fcmToken ?? ""]
print("Device token: ", deviceToken) // This token can be used for testing notifications on FCM
}
}
@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
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: (messageID)")
}
print(userInfo)
// Change this to your preferred presentation option
completionHandler([[.banner, .badge, .sound]])
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID from userNotificationCenter didReceive: (messageID)")
}
print(userInfo)
completionHandler()
}
}
It seems to be the same coding. 😐
Thank you all so much
Seraphel Kay Jesus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.