Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

239
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda