Search code examples
iosswiftuitableviewuirefreshcontrol

How can I allow a user to only refresh a table every "n"th second?


I added a a UIRefreshControl to my tableview so that I could allow the user to pull to refresh.

They do not need to refresh it constantly, only every 30 seconds. How can I allow them to only do it every 30 seconds?

@IBOutlet weak var tableView: UITableView!

private let refresher: UIRefreshControl = UIRefreshControl()

override func viewDidLoad() {
    super.viewDidLoad()

    //load Event data
    loadData()

    // Add Refresh Control to Table View
    tableView.refreshControl = refresher

    refresher.addTarget(self, action: #selector(refreshData(_:)), for: .valueChanged)
    refresher.attributedTitle = NSAttributedString(string: "Fetching events...")

}

@objc private func refreshData(_ sender: Any) {
    // Fetch Data
    loadData()
}


private func loadData() {
     //code here for grabbing data
}

Solution

  • Very simple; every time the user refreshes, you store the Date in a property, and the next time, if 30 seconds have not elapsed, you do nothing.