Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

244
Vistas
actualizar la vista de la tabla cuando se recibe una notificación

Tengo un chat muy pequeño en mi aplicación. cada vez que un usuario recibe un mensaje, el servidor envía una notificación. En appDelegate he implementado el siguiente código:

 @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler(.alert) // print(UNNotificationAction) print("📲📲📲 recieved") if notification.request.content.title.contains("Message") { print("sub") print(notification.request.content.subtitle) print("body") print(notification.request.content.body) print("it containt DM ⏰") let storyboard:UIStoryboard = UIStoryboard(name:"Chat", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "chatRoomVc") as! ChatRoomViewController vc.becomeFirstResponder() vc.setRefreshListener { print("triggered") } } }

y cada vez que se ejecuta, llama a la API y obtiene los datos del chat. el siguiente código muestra cómo obtiene los datos:

 func setRefreshListener(listener:@escaping ()->Void){ refreshListener = listener presenter.getttingChatRoomData(aptId: UserDefaults.standard.string(forKey: userAPTID)!, id: UserDefaults.standard.string(forKey: userID)!) presenter.attachView(view: self) super.loadView() super.reloadInputViews() tableView.reloadData() }

además, puedo obtener los datos correctamente.

¡¡EL PROBLEMA es que no recarga los datos para la vista de tabla!!

¿alguien tiene alguna solución de por qué sucede esto?

ACTUALIZACIÓN: el siguiente código se ejecuta cuando se reciben los datos:

 func gettingUserChatWithSUCCESS(responce: [chatRomModel]) { print("✅ getting chat room data SUCCESS") data = responce tableView.reloadData() }
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Puede resolver este problema utilizando el observador de notificaciones, siga este código.

Agregue un observador de notificaciones en su controlador de vista

 NotificationCenter.default.addObserver(self, selector: #selector(onReceiveData(_:)), name: "ReceiveData", object: nil) @objc func onReceiveData(_ notification:Notification) { // Do something now //reload tableview }

llamar al observador usando este código en su archivo appDelegate.swift recibir método de notificación

 NotificationCenter.default.post(name: Notification.Name("ReceiveData"), object: nil)

Nota: - Elimine el observador de notificaciones cuando desaparezca su controlador de vista, usando este código

 override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self, name: "ReceiveData", object: nil) }
over 4 years ago · Santiago Trujillo Denunciar

0

Implemente el método UNUserNotificationCenterDelegate y publique su notificación.

 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo if UIApplication.shared.applicationState == .background || UIApplication.shared.applicationState == .inactive { NotificationCenter.default.post(name: .newMessage, object: nil, userInfo:userInfo) } }

En su controlador de vista, agregue un observador para verificar las notificaciones (Agregue su propio método de selección).

 NotificationCenter.default.addObserver(self, selector: #selector(updateMessages(notification:)), name: .newMessage, object: nil) @objc func updateMessages(notification: NSNotification) { // Handle your notifications... }
over 4 years ago · Santiago Trujillo Denunciar

0

INCLUIDO CON SWIFT 5.4

 let myNotificationKey = "notificationKey" //Declare variable at the global level NotificationCenter.default.addObserver(self, selector: #selector(notifyMe), name: NSNotification.Name(rawValue: myNotificationKey), object: nil) //In First VC's viewDidLoad() func notifyMe() { print("Update tableview") } //In First VC NotificationCenter.default.post(name: Notification.Name(rawValue: myNotificationKey), object: self) //Use this from you want to update the notification center for eg: OnClick of UIButton
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda