rob rob - 13 days ago 38
iOS Question

Pull to refresh and Alamofire using Swift 3

I am using Alamofire to get data from a web url (JSON). I am trying to implement pull to refresh into my project. I have done it but don't know if it is correct or if the data is getting updated when refreshed. my code is:

var refresh = UIRefreshControl()

refresh.addTarget(self, action: #selector(self.refreshData), for: UIControlEvents.valueChanged)

func refreshData() {

Alamofire.request("https://www.example.com/api").responseJSON(completionHandler: {
response in
self.parseData(JSONData: response.data!)
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine

self.tableView.reloadData()
self.refresh.endRefreshing()


})

}


Is this correct?

Answer

You are doing correctly but you need reload tableView and stop UIRefreshControl on main thread.

DispatchQueue.main.async {
    self.tableView.reloadData()
    self.refresh.endRefreshing()             
}

Note: Instead of setting separatorStyle always on API request you need to set it once with viewDidLoad or with Interface builder.