When my app is active and I receive a silent notif from the server to update my tableview with the new data, I'm calling the following function in which I'm making a request to the server to bring latest data and then reload that specific row.
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()
}
}
}
}
}
}
My problem is when my app is in the foreground the flow doesn't work anymore because of the API request which can't be done in the foreground / background .
Console log shows :
load failed with error Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort"
I've tried to modify my function with
let state = UIApplication.shared.applicationState
if state == .background || state == .inactive {
NotificationCenter.default.addObserver(self, selector: #selector(self.reloadData(_:)), name: NSNotification.Name("BackgroundReload"), object: nil)
}
and posted this "BackgroundRelod" notification in AppDelegate
func applicationWillEnterForeground(_ application: UIApplication)
but this will always trigger my function even though I didn't receive any silent notification to update the UI.
You should not depend on background mode in updates , you need to only modify a var say needsUpdate
whenever a silent notification comes in background here
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
Then
NotificationCenter.default.addObserver(self, selector: #selector(update), name: UIApplication.willEnterForegroundNotification, object: nil)
@objc func ppp(_ no:NSNotification) {
if needsUpdate {
// pull here
}
}