简体   繁体   中英

Reload tableview realtime in Swift 3

How to reload tableview in realtime using timer ? If viewed, logs are always realtime but in tableview they're not. Is there anything less than my coding?

@IBOutlet var tableViewChat: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    tableViewChat = UITableView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), style: UITableViewStyle.plain)

    startTimer()
}

func startTimer() {
    timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(GetOrders), userInfo: nil, repeats: true)
    timer.fire()
}

func stopTimer() {
    timer.invalidate()
    timer = nil
}

func GetOrders() {
    getUserOnline()
    getChatMessage()
    DispatchQueue.main.async {
        self.tableViewChat.reloadData()
    }
}

Try changing height of tableview. Now its 0, so I think its not displaying tableview. As your logs are showing properly, as per my knowledge there should be issue with table view height.

Your tableViewChat is initialised I storyboard so you don't need this line:

tableViewChat = UITableView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), style: UITableViewStyle.plain)

if you want to change the style do it in storyboard.

Also it looks like you are getting the data asynchronous:

getUserOnline()
getChatMessage()

Which means that it may take some time to have the data back but you reload the table view straight away:

DispatchQueue.main.async {
    self.tableViewChat.reloadData()
}

At that stage you may not have the data at all (so that's why your table view is empty). You need a completion handler or delegate which fires once the data is downloaded and then reload the table view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM