Search code examples
iosswiftpull-to-refreshuirefreshcontrol

UIRefreshControl does not work


My project is still using Swift 2.3 and is not migrated to Swift 3 yet. When I pull down table view with the following code I can verify that refreshed data can be seen in Debug Area, but it doesn't reflect on the table view. I tried it both on IOS 9 and IOS 10.

 var refreshControl = UIRefreshControl()

 if #available(iOS 10.0, *) {
    TableView.refreshControl = refreshControl
 } else {
    TableView.addSubview(refreshControl)
 }

 refreshControl.addTarget(self, action: #selector(self.handleRefresh), forControlEvents: UIControlEvents.ValueChanged)

 func handleRefresh(refreshControl: UIRefreshControl) {
     refreshControl.beginRefreshing()

     Search()
     TableView.reloadData()

     refreshControl.endRefreshing()
 }

Solution

  • Move tableView.reloadData() to a place where you can be sure the search() function has completed and returned results. If that is an async function then add a completion handler so that you know when to call reloadData(). Then you could call the function like so:

    search {
        dispatch_async(dispatch_get_main_queue()) {
            tableView.reloadData()
        }
    }
    

    Or, when you're on Swift 3

    DispatchQueue.main.async {...}