Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic refreshing tableview without pulling to refresh

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?

like image 325
Jae Kim Avatar asked Jan 07 '23 14:01

Jae Kim


1 Answers

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()
        }
    }
}
like image 191
Dharmesh Kheni Avatar answered Feb 03 '23 09:02

Dharmesh Kheni