I'm working on a chat app and I configured a function to check if a user is online. I'm able to see if another user is active or not, but, the issue I'm having is that if I scroll down (I'm using a UITableView) other users show as active and they are not. I placed the code inside the UITableViewCell class. Any suggestions as to what could be the problem are greatly appreciated. Here is my code:
UITableViewCell
`func configureHomeFeedCell(member: Member) {
profileImage.loadImage(with: member.imageURL)
profileName.text = "\(member.name)" + ", " + "\(member.age)"
checkUserOnlineStatus(with: member.documentId) { _ in }
}
func checkUserOnlineStatus(with userId: String, completion: @escaping(Bool) -> Void) {
let query = USERS_COLLECTION.document(userId).collection(IS_ONLINE)
query.getDocuments { (snapshot, error) in
if let error = error {
print("ERROR..\(error.localizedDescription)")
} else {
snapshot?.documents.forEach({ diff in
let isOnline = diff.get(USER_IS_ONLINE) as? Bool
self.onlineViewStatus.backgroundColor = isOnline == true ? .green : .red
completion(isOnline!)
})}}
query.addSnapshotListener { (snapshot, error) in
snapshot?.documentChanges.forEach { diff in
let isOnline = diff.document.get(USER_IS_ONLINE) as? Bool
if (diff.type == .modified) {
self.onlineViewStatus.backgroundColor = isOnline == true ? .green : .red
completion(isOnline!)
}}}
}`
What would such a delegate do? Your onlineViewStatus view (btw, would the name be more clear as onlineStatusView?) seems to be just an “output” via its background color, and doesn’t seem to have any actual behavior that would need to be reported via a delegate back to the view controller. Is this correct?
Try to make the cell behavior as simple as possible: you have an image, a name, and a view that shows online status. You already get the image and name from the Member object which is passed to the cell during configuration. Similarly, now you’ll want to pass the online status to the cell when you receive it, and then the cell just sets the color. Then the cell class becomes extremely simple.
The fun starts at “pass the online status to the cell when you receive it.” So the view controller would launch async operation(s) to fetch everyone’s online status, and then updates the cell for each member when that member’s online status is received. The best way to do this is to build your table using a diffable data source. (If you’re not already using this, I strongly recommend it. It makes things much easier.) Then you use the diffable data source snapshot to tell the table to redraw the cells that need updating.