Reputation: 223
I am using tableview to show some data from json. I am using an array of object to populate those data. Now I want to refresh those data after a certain time(e.g. 10 sec) like yahoo cricket mobile app. Can any one please suggest me how can I do this?
Upvotes: 2
Views: 1517
Reputation: 2698
Schedule a timer which run for every 10 sec as
timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selectior(refresh), userInfo: nil, repeats: false)
}
func refresh() {
// fetch Data from Server
}
After fetching the data, populate your array again and use tableView method reloadData
to reload the tableView
tableview.reloadData()
To update some rows of the data you can use code below. Here I'm demonstrating one row update, you can do the same with multiple row update by passing as many as indexPath
in an array you want
//suppose you want to update row 0 for section 0, create indexPath as
let indexPath1 = NSIndexPath(forRow: 0, inSection: 0)
tableview.reloadRowsAtIndexPaths([indexPath1], withRowAnimation: .Automatic)
If you want to update your particular section, do this
//suppose you want to update your section 0
let indexSet = NSIndexSet(index: 0)
profileTableView.reloadSections(indexSet, withRowAnimation: .Automatic)
Upvotes: 0
Reputation: 4533
Using timers is one way you can do it, In ViewDidload
self.myTimer = NSTimer(timeInterval: 10.0, target: self, selector: "refresh", userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(self.myTimer, forMode: NSDefaultRunLoopMode)
func refresh() {
tableview.reloadData(); //refresh the table
}
Upvotes: 2
Reputation: 5586
The most easy way is to use an NSTimer.
class ViewController: UIViewController {
var timer : NSTimer!
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selectior(fetch), userInfo: nil, repeats: false)
}
func fetch() {
// do your stuff here
}
}
Upvotes: 0