Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Firebase Messaging: Fails to receive a notifications in iOS - SwiftUI #8738

Closed
gabrielcosi opened this issue Oct 3, 2021 · 4 comments · Fixed by #9152
Closed

Firebase Messaging: Fails to receive a notifications in iOS - SwiftUI #8738

gabrielcosi opened this issue Oct 3, 2021 · 4 comments · Fixed by #9152
Assignees
Labels
api: messaging SwiftUI Issues directly related to Apple's SwiftUI framework

Comments

@gabrielcosi
Copy link

[REQUIRED] Step 1: Describe your environment

  • Xcode version: 13
  • Firebase SDK version: 8.8.1
  • Installation method: Swift Package Manager
  • Firebase Component: Messaging

[REQUIRED] Step 2: Describe the problem

Device doesn't receive a notification with basic setup from firebase docs in SwiftUI. Already tested sending it directly via APNs and it works as expected.

Steps to reproduce:

What happened? How can we make the problem occur?
8.8.1 - [Firebase/Messaging][I-FCM001000] FIRMessaging Remote Notifications proxy enabled, will swizzle remote notification receiver handlers. If you'd prefer to manually integrate Firebase Messaging, add "FirebaseAppDelegateProxyEnabled" to your Info.plist, and set it to NO. Follow the instructions at: https://firebase.google.com/docs/cloud-messaging/ios/client#method_swizzling_in_firebase_messaging to ensure proper integration. Permission granted: true Notification settings: <UNNotificationSettings: 0x282741440; authorizationStatus: Authorized, notificationCenterSetting: Enabled, soundSetting: Enabled, badgeSetting: Enabled, lockScreenSetting: Enabled, carPlaySetting: NotSupported, announcementSetting: Disabled, criticalAlertSetting: NotSupported, timeSensitiveSetting: NotSupported, alertSetting: Enabled, scheduledDeliverySetting: Disabled, directMessagesSetting: NotSupported, alertStyle: Banner, groupingSetting: Default providesAppNotificationSettings: No> 8.8.1 - [Firebase/Messaging][I-FCM002022] APNS device token not set before retrieving FCM Token for Sender ID '807357529171'. Notifications to this FCM Token will not be delivered over APNS.Be sure to re-retrieve the FCM token once the APNS device token is set.

If you have a downloadable sample project that reproduces the bug you're reporting, you will
likely receive a faster response on your issue.

Relevant Code:

//
//  MyApp.swift
//  MyApp
//
//  Created by Gabriel Cosi on 28/09/21.
//

import SwiftUI
import Firebase
import UserNotifications

@main
struct MyApp: App {
    
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

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
              
        UNUserNotificationCenter.current()
          .requestAuthorization(
            options: [.alert, .sound, .badge]) { granted, _ in
            print("Permission granted: \(granted)")
            guard granted else { return }
            UNUserNotificationCenter.current().getNotificationSettings { settings in
                print("Notification settings: \(settings)")
                guard settings.authorizationStatus == .authorized else { return }
                DispatchQueue.main.async {
                  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)")
        }
        
        guard let aps = userInfo["aps"] as? [String: AnyObject] else {
            completionHandler(.failed)
            return
          }
        print("got something, aka the \(aps)")

        // Print full message.
        print(userInfo)

        completionHandler(UIBackgroundFetchResult.newData)
      }
    
      func application(_ application: UIApplication,
                       didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Unable to register for remote notifications: \(error.localizedDescription)")
      }

      
      func application(_ application: UIApplication,
                       didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
          print("device token")
          let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
          let token = tokenParts.joined()
          print("Device Token: \(token)")
      }
    
}

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

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // ...

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
      completionHandler([[.banner, .badge, .sound]])
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo

    print(userInfo)

    completionHandler()
  }
}

extension AppDelegate: MessagingDelegate {
  // [START refresh_token]
  func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
    print("Firebase registration token: \(String(describing: 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.
  }

  // [END refresh_token]
}

@KBRR11
Copy link

KBRR11 commented Oct 6, 2021

ya revisaste en XCode si tienes esto?

Captura de Pantalla 2021-10-06 a la(s) 15 48 40

solo por si acaso :v saludos amiko

@gabrielcosi
Copy link
Author

ya revisaste en XCode si tienes esto?

Captura de Pantalla 2021-10-06 a la(s) 15 48 40

solo por si acaso :v saludos amiko

image

@levibostian
Copy link

I was able to fix this problem by disabling FCM method swizzling and handling methods myself. I found that it's because I am building a SwiftUI app like yourself that is the reason for the issue. For a full walkthrough, I used this guide which goes over setup with SwiftUI.

@paulb777 paulb777 added the SwiftUI Issues directly related to Apple's SwiftUI framework label Nov 16, 2021
@charlotteliang
Copy link
Contributor

@levibostian Your case might be different than @gabrielcosi since this bug is still using the AppDelegate lifecycle. Would you mind create a separate issue? Thank you!

@gabrielcosi I am not able to reproduce since our sample app has the same setup. . Would you mind send me the debugLog or compare with our sample app to see if what's your setup might be different?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
api: messaging SwiftUI Issues directly related to Apple's SwiftUI framework
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants