OK, I had to think about this one more time and i finally got it working 100%. Aside from the call to get all the user documents, I was making another call at the same time to the collection that was storing the values for isOnline. I added isOnline to the members model and a separate snapshot listener to monitor the changes to that key. Now everything is working 100%. Hope this helps anyone.
I have updated my code:
Service Class
**This function is to update the user's presence when online or not and it's called inside SceneDelegate **
static func isUserOnline(bool: Bool) {
guard let currentUID = Auth.auth().currentUser?.uid else { return }
if !currentUID.isEmpty {
let dictionary = [USER_IS_ONLINE: bool as Any,
USER_LASTEST_ONLINE: Date().timeIntervalSince1970 as Any]
USERS_COLLECTION.document(currentUID).getDocument { (document, error) in
if let error = error {
print("Error..\(error.localizedDescription)")
} else {
if document?.exists == true {
USERS_COLLECTION.document(currentUID).updateData(dictionary)
} else {
USERS_COLLECTION.document(currentUID).updateData(dictionary)
}}}}}
**SceneDelegate**
func sceneDidDisconnect(_ scene: UIScene) {
Service.isUserOnline(bool: false)
}
func sceneDidBecomeActive(_ scene: UIScene) {
Service.isUserOnline(bool: true)
}
func sceneWillResignActive(_ scene: UIScene) {
Service.isUserOnline(bool: false)
}
func sceneDidEnterBackground(_ scene: UIScene) {
Service.isUserOnline(bool: false)
}
**This function is to monitor the user activity**
static func checkUserOnlineStatus(with userId: String, completion: @escaping(Bool) -> Void) {
let query = USERS_COLLECTION.document(userId)
query.getDocument { (document, error) in
if let document = document, document.exists {
let isOnline = document.get(USER_IS_ONLINE) as? Bool ?? false
completion(isOnline)
}
}
query.addSnapshotListener { (document, error) in
if let document = document, document.exists {
let isOnline = document.get(USER_IS_ONLINE) as? Bool ?? false
completion(isOnline)
}}}
Calling the function inside the cell class
func configureHomeFeedCell(member: Member) {
Service.checkUserOnlineStatus(with: member.documentId) { isOnline in
self.onlineViewStatus.backgroundColor = isOnline == true ? .green : .red
} }
Topic:
Programming Languages
SubTopic:
Swift
Tags: