I want to know how to automatically refresh a tableview without having to pull down to refresh. So I tried setting an NSTimer
and calling a function that has reloadData()
. But that did not work. In other words, I did:
@IBOutlet weak var allPrayerRequestsTableView: UITableView!
var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)
func update() {
allPrayerRequestsTableView.reloadData()
}
But this did not work. Anybody know how to automatically refresh a tableview every few seconds?
Try to reload your tableview in main thread this way:
dispatch_async(dispatch_get_main_queue()) {
self.allPrayerRequestsTableView.reloadData()
}
And your method will be:
func update() {
dispatch_async(dispatch_get_main_queue()) {
self.allPrayerRequestsTableView.reloadData()
}
}
Sample code:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var allPrayerRequestsTableView: UITableView!
var tableArray = [Int]()
var count = 0
override func viewDidLoad() {
super.viewDidLoad()
allPrayerRequestsTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
allPrayerRequestsTableView.delegate = self
allPrayerRequestsTableView.dataSource = self
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return tableArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel?.text = "\(tableArray[indexPath.row])"
return cell
}
func update() {
count++
//update your table data here
tableArray.append(count)
dispatch_async(dispatch_get_main_queue()) {
self.allPrayerRequestsTableView.reloadData()
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With