rob
rob

Reputation: 301

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 RefreshControl 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?

Upvotes: 0

Views: 839

Answers (1)

Nirav D
Nirav D

Reputation: 72410

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.

Upvotes: 2

Related Questions