Home > database >  delay endRefreshing for 2 seconds after processing web query in Swift
delay endRefreshing for 2 seconds after processing web query in Swift

Time:10-27

I have a website query to get updated "Alert" statuses

I have an AlertManager with an AlertManagerDelegate protocol, and I am implementing this protocol in an AlertsTableViewController

One of the functions of this protocol is "didUpdateAlerts" as seen below, which is ultimately triggered after a successful query following a pull-to-refresh

func didUpdateAlerts(alerts: [String:String]){
    
    DispatchQueue.main.async {
        self.serviceDictionary = alerts
        self.tableView.reloadData()
    }
}

I would like to stick an endRefreshing with a one second delay following reloading the tableView data (for a smoother user experience)

Because the data is queried very quickly, if I add the endRefreshing below the reloadData() call, the refreshing animations ends almost instantaneously. How can I implement the delay?

Edited code -- appears to work but sometimes the print statement prints more than once, and sometimes the delay is still shorter than the assigned time

DispatchQueue.main.async {
        self.serviceDictionary = alerts
        self.tableView.reloadData()
        //self.perform(#selector(self.stopRefreshing), with: nil, afterDelay: 5)
        DispatchQueue.main.asyncAfter(deadline: .now()   3.0) {
            self.refreshAlertsControl.endRefreshing()
            print("After 3 sec delay - alertRefresh")
        }
}

CodePudding user response:

You can use asyncAfter func to submit a work item onto a dispatch queue for asynchronous execution after a specified time. You probably do not need a whole second, usually 0.3 of a second is enough but the example shows a 5 second execution delay.

  DispatchQueue.main.async {
     self.tableView.reloadData()
     print("Before delay")
     DispatchQueue.main.asyncAfter(deadline: .now()   5.0) {
        self.refreshControl.endRefreshing()
         print("After 5 sec delay")
     }
  }
  • Related