首页 > 解决方案 > 应用程序在前台时如何更新 UI?

问题描述

当我的应用程序处于活动状态并且我收到来自服务器的静默通知以使用新数据更新我的 tableview 时,我正在调用以下函数,在该函数中我向服务器发出请求以获取最新数据,然后重新加载该特定数据排。

func updateCell(path: Int, messageId: String) {
    let indexPath = IndexPath(item: path, section: 0)
    if let visibleIndexPaths = mainTableView.indexPathsForVisibleRows?.index(of: indexPath as IndexPath) {
        if visibleIndexPaths != NSNotFound {
            if let id = self.userData?.id {
                let conversationID = String(describing: id)
                ServerConnection.getSpecificMessage(conversationId: conversationID, messageId: messageId) { (dataMessage) in
                    if let message = dataMessage {
                        self.chat[path] = message
                        self.mainTableView.beginUpdates()
                        self.mainTableView.reloadRows(at: [indexPath], with: .fade)
                        self.mainTableView.endUpdates()
                    }
                }
            }
        }
    }
}

我的问题是当我的应用程序处于前台时,由于 API 请求无法在前台/后台完成,因此流程不再起作用。

控制台日志显示:

加载失败,错误域 = NSPOSIXErrorDomain 代码 = 53“软件导致连接中止”

我试图修改我的功能

let state = UIApplication.shared.applicationState
    if state == .background || state == .inactive {
        NotificationCenter.default.addObserver(self, selector: #selector(self.reloadData(_:)), name: NSNotification.Name("BackgroundReload"), object: nil)
    }

并在 AppDelegate 中发布了这个“BackgroundRelod”通知

func applicationWillEnterForeground(_ application: UIApplication)

但这总是会触发我的功能,即使我没有收到任何更新 UI 的静默通知。

标签: iosswiftpush-notificationforeground

解决方案


您不应该在更新中依赖后台模式,您只需要修改一个 var sayneedsUpdate每当后台出现静默通知时

func application(_ application: UIApplication,
                 didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

然后

NotificationCenter.default.addObserver(self, selector: #selector(update), name: UIApplication.willEnterForegroundNotification, object: nil)

@objc func ppp(_ no:NSNotification) {

    if needsUpdate {

        // pull here
    }

}

推荐阅读