how can I refresh data in a collection view in swift 4?

Viewed 11966

I have a function to refresh the data of an array every 2 seconds

var timer = Timer()

func timeRefresh(){
    timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(ViewController.refreshData), userInfo: nil, repeats: true)

}

I receive the data from a post service

@objc func refreshData(){

    post(postString, Route) { (res) in

        let success = res["success"]

        if success == true {
            let walkers = res["walkers"]

            for secondItem in walkers.array! {
                let duration = secondItem["duration"]

                self.timeCar.append(duration.stringValue) //this is the info that i need for the collection view

                }
            }

            print("array time \(self.timeCar)")

        }else{
            self.timeCar = ["-.-","-.-","-.-","-.-","-.-"]
        }
    }
}

I need refresh the collection view every second

cell.typeLabel.text = timeCar[indexPath.row]
1 Answers

UICollectionView has multiple ways of reloading data.

If you want every cell to be reloaded: collectionView.reloadData().

If you want a specific section to be reloaded: collectionView.reloadSections(<Array of Sections>).

If you want to reload specific cells: collectionView.reloadItems(<Array of IndexPaths>).

Related