0

So I'm trying to implement Cloud Messaging with Firebase Functions for a message center in my app. My firebase function says it is already working and I do receive the message in my console log, however, the notification is not being deployed in my phone on background mode.

I've implemented the permission to receive notifications once my user is logged in in Home View. This is my code:

 func askNotificationPermission() {
        
        //Firebase Push Notifications
          UNUserNotificationCenter.current().delegate = self

          let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
          UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in
                print("HOLA TE DIERON PERMISO")
          })
        
            Messaging.messaging().shouldEstablishDirectChannel = true
        
          UIApplication.shared.registerForRemoteNotifications()
          Messaging.messaging().delegate = self
  
    }

I've implemented the necessary Firebase functions in didFinishLaunchingApplication:

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    //MARK: Firebase
    FirebaseApp.configure()
    
    //Firebase Cloud Messaging
      Messaging.messaging().delegate = self
    
    
    //MARK: Others
    //KeyboardManager
    IQKeyboardManager.shared.enable = true
    
    //navbar
    let navControl = UINavigationBar.appearance()
    let myColor : UIColor = UIColor(red: 0, green: 0.1333, blue: 0.3176, alpha: 1)
    navControl.tintColor = myColor

    return true
}

And this is my extension for the Notifications within App Delegate:

    extension AppDelegate: UNUserNotificationCenterDelegate, MessagingDelegate {
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        Messaging.messaging().shouldEstablishDirectChannel = true
    }
    
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
           
           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 application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        
        Messaging.messaging().appDidReceiveMessage(userInfo)
        
        if let messageID = userInfo[gcmMessageIDKey] {
           print("Message ID: \(messageID)")
         }

         // Print full message.
         print("USER INFO: ",userInfo)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print(userInfo)
        completionHandler(UIBackgroundFetchResult.newData)
        print("USER INFO IN DID RECEIVE REMOTE NOTIFICAITON:", userInfo, UIBackgroundFetchResult.newData)
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        let userInfo = notification.request.content.userInfo as! [String:Any]

        completionHandler([.alert, .badge, .sound])
        print("HOLI")

    }
}

I don't know what might be the problem and why I am receiving the information in the console but it is not being pushed to the app. I've searched through several stackoverflow questions but none have worked.

This is what my console logs:

2020-08-06 11:06:06.804344-0500 FleaMarket_UserSide[13985:4429211] [] nw_read_request_report [C2] Receive failed with error "Software caused connection abort" [AnyHashable("title"): Jay Shetty Meditations, AnyHashable("aps"): { "content-available" = 1; }, AnyHashable("gcm.message_id"): 1596729966264394, AnyHashable("message"): did you get it?, AnyHashable("google.c.sender.id"): 520471783461] USER INFO IN DID RECEIVE REMOTE NOTIFICAITON: [AnyHashable("title"): Jay Shetty Meditations, AnyHashable("aps"): { "content-available" = 1; }, AnyHashable("gcm.message_id"): 1596729966264394, AnyHashable("message"): did you get it?, AnyHashable("google.c.sender.id"): 520471783461] UIBackgroundFetchResult 2020-08-06 11:06:06.835793-0500 FleaMarket_UserSide[13985:4429216] 6.27.0 - [Firebase/Firestore][I-FST000001] WatchStream (282c75618) Stream error: 'Unavailable: Socket is not connected'

NicolasElPapu
  • 1,612
  • 2
  • 11
  • 26
  • try this https://stackoverflow.com/questions/49522284/firebase-messenger-sends-a-notification-but-ios-device-doesnt-receive-anything/49526890#49526890 enable the service – naga Aug 06 '20 at 21:48
  • are u enable remote notification service if you not at done https://stackoverflow.com/questions/30979218/no-push-notification-capability-in-xcode – naga Aug 06 '20 at 21:49
  • @naga I already set FirebaseAppDelegateProxyEnabled to YES, and still I don't get it – Ximena Flores de la Tijera Aug 06 '20 at 23:28
  • @naga and by enabled remote notifications service... do you mean in capabilities? If that's the case, then YES. I already have it enabled. And I do get push notifications when I send them through CLOUD MESSAGING inside Firebase – Ximena Flores de la Tijera Aug 06 '20 at 23:30
  • Hello, did you tried to achieve this following any guide or tutorial? did you tried [this](https://www.iosapptemplates.com/blog/ios-development/push-notifications-firebase-swift-5) for example? – Chris32 Aug 07 '20 at 13:12
  • @Chris32 I'm taking a look at it, it does look a bit more organized than mine. I'll let you know the outcome but from first view, it appears as if I have everything. Don't know if it might be an issue related to cloud functions – Ximena Flores de la Tijera Aug 07 '20 at 14:35
  • Well, if you already added the permissions in the info.plist file it is possible that this may an issue with Cloud Functions. Are you able to communicate your application with Firebase at all? – Chris32 Aug 07 '20 at 15:46
  • @Chris32 by permissions in the info.plist file you mean the (FirebaseAppDelegateProxyEnabled to YES)? And yes. The crazy thing is that I do receive the message sent through firebase in my console, I get it but it is not being displayed as push notification. – Ximena Flores de la Tijera Aug 07 '20 at 16:01
  • Please, let us know if you found the answer or if you are still experiencing the issue – Juancki Aug 11 '20 at 13:47
  • @Juancki I am unfortunately still looking for the answer. :( – Ximena Flores de la Tijera Aug 11 '20 at 15:37

1 Answers1

1

I found my error. It was in my firebase function. I had written my payload incorrectly. I had written:

var newmessage = { data: { title: groupName, body: message }, topic: offerTopic, };

The correct payload according to Firebase documentation is NOTIFICATION:

var newmessage = {
      notification: {
        title: groupName,
        body: message
      },
      topic: offerTopic,
    };

Make sure to stick to the firebase cloud message documentation found here, or it won't take it as a notification and won't push it.

https://firebase.google.com/docs/cloud-messaging/ios/topic-messaging