ios - 应用程序在前台时如何更新 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 的静默通知。
解决方案
您不应该在更新中依赖后台模式,您只需要修改一个 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
}
}
推荐阅读
- data-binding - 组件创建顺序
- qt - 如何使用 QMake 获取平台相关的输出文件名?
- javascript - 鼠标进入时为页面上的任何元素添加一个类,离开时删除
- ubuntu - 在 Azure DevOps 中更新 Microsoft 托管代理上的 CMake
- css - float:left 重叠在其他元素上
- keil - Keil uvision5. A51 how properly assign labels to and address bits in memory
- reactjs - 无法在反应本机应用程序中导入 React Bootstrap 组件
- ios - swift Kingfisher and MPMediaItemArtwork
- machine-learning - Can we do performed both feature selection and PCA?
- c++ - 如何根据模板类型定义浮点常量?