0

Tengo actualmente una app de chat tanto en android(java) como en iOS(swift) y ambas funcionan con la misma base de datos en Firebase. necesito ayuda para configurar las notificaciones push en segundo plano ya que lo he intentado y nada.

Si envio un mensaje con un usuario android a un usuario iOS no llegan las notificaciones cuando la app ios esta en segundo plano, pero de android a android, de ios a ios y de ios a android si llegan.

De android a ios solo llegan si el usuario ios esta dentro de la app, pero necesito que lleguen las notificaciones ios cuando la app este cerrada o en segundo plano.

en iOS ya tengo configurados los certificados necesarios de apple y el proyecto firebase

necesito de su apoyo.

Adjunto el codigo fuente:

AppDelegate.swift

     @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {

    let gcmMessageIDKey = "gcm.message_id"
        var window: UIWindow?

        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {


            // Override point for customization after application launch.
            FirebaseApp.configure()


            // [START set_messaging_delegate]
            Messaging.messaging().delegate = self
            // [END set_messaging_delegate]
            // Register for remote notifications. This shows a permission dialog on first run, to
            // show the dialog at a more appropriate time move this registration accordingly.
            // [START register_for_notifications]
            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()
            // [END register_for_notifications]


            //let pushManager = PushNotificationManager(userID: Auth.auth().currentUser!.uid)
            //pushManager.registerForPushNotifications()




            GMSPlacesClient.provideAPIKey("AIzaSyAUapKf62FHGkHVbpc6HY8R7qncJ83-R10")
            GMSServices.provideAPIKey("AIzaSyAUapKf62FHGkHVbpc6HY8R7qncJ83-R10")
            IQKeyboardManager.shared.enable = true
            GADMobileAds.sharedInstance().start(completionHandler: nil)


            return true
        }

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
          // If you are receiving a notification message while your app is in the background,
          // this callback will not be fired till the user taps on the notification launching the application.
          // TODO: Handle data of notification
          // 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 full message.
          print(userInfo)
        }

        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                         fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
          // If you are receiving a notification message while your app is in the background,
          // this callback will not be fired till the user taps on the notification launching the application.
          // TODO: Handle data of notification
          // 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 full message.
          print(userInfo)

          completionHandler(UIBackgroundFetchResult.newData)


  } 
     func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("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 FCM registration token.
      func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("APNs token retrieved: \(deviceToken)")

        // With swizzling disabled you must set the APNs token here.
        Messaging.messaging().apnsToken = deviceToken
      }
    }

@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

    // 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 full message.
    print(userInfo)

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

  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)")
    }

    // Print full message.
    print(userInfo)

    completionHandler()
  }
}

extension AppDelegate : MessagingDelegate {
  func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")

    let dataDict:[String: String] = ["token": fcmToken]
    let ref = Database.database().reference()
    let uid = Auth.auth().currentUser?.uid ?? ""
    if uid != "" {
        ref.child("Tokens").child(uid).updateChildValues(dataDict)
    }
    NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)    
  }
  Messaging.messaging().shouldEstablishDirectChannel to true.
  func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("Received data message: \(remoteMessage.appData)")
  }
}

La funcion que uso para enviar la notificacion:

func sendPushNotification(payloadDict: [String: Any]) {
       let url = URL(string: "https://fcm.googleapis.com/fcm/send")!
       var request = URLRequest(url: url)
       request.setValue("application/json", forHTTPHeaderField: "Content-Type")
       // get your **server key** from your Firebase project console under **Cloud Messaging** tab
       request.setValue("key= aqui va mi server key", forHTTPHeaderField: "Authorization")
       request.httpMethod = "POST"
       request.httpBody = try? JSONSerialization.data(withJSONObject: payloadDict, options: [])
       let task = URLSession.shared.dataTask(with: request) { data, response, error in
          guard let data = data, error == nil else {
            print(error ?? "")
            return
          }
          if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print(response ?? "")
          }

          print("Notification sent successfully.")
          let responseString = String(data: data, encoding: .utf8)
          print(responseString ?? "")
       }
       task.resume()
    }

y asi es como llamo esa funcion:

let notifPayload: [String: Any] = ["to": self.token!, "notification": ["title": self.usernamelbl.text!,"body": self.msgtf.text! ,"badge":1,"sound":"default"]]
                        self.sendPushNotification(payloadDict: notifPayload)

Saludos.

7
  • Y de anndroid a android funciona? De ios a ios? De ios a android?
    – ffflabs
    el 29 feb. 2020 a las 18:18
  • De Android a Android funciona perfecto, de iOs a iOs también, de Android a iOs es donde esta el problema solo recibe cuando en iOs esta dentro del Chat :-( el 2 mar. 2020 a las 3:03
  • O sea los chat los mandas con payload de datamesssge, no de notificación. Pero imagino que no los mandas directo sino que pasan por cloud functions o por tu backend?
    – ffflabs
    el 2 mar. 2020 a las 5:06
  • Si pasa por firebase el 3 mar. 2020 a las 12:52
  • Debería ser Firebase quien envíe las notificaciones y no la aplicación móvil. Esto lo puedes hacer con Firebase Cloud Functions. Esto permite que cada vez que se actualize un campo de tu base de datos Firebase se ejecute algo, ese algo puede ser enviar una notificación. el 5 mar. 2020 a las 21:27

1 respuesta 1

0

Quizás te falta agregar el background mode, en la sección de Signing & Capabilities

Background

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.