英文:
Firebase chat fetch and delete particular chat call firebase real time socket continuously
问题
以下是您提供的代码的翻译:
获取消息函数
/// 获取并返回用户通过传入的电子邮件创建的所有会话
public func getAllConversations(for email: String, completion: @escaping (Result<[Conversation], Error>) -> Void) {
    database.child("\(email)/conversations").observe(.value, with: { snapshot in
        guard let value = snapshot.value as? [[String: Any]] else {
            completion(.failure(DatabaseError.failedToFetch))
            return
        }
        let conversations: [Conversation] = value.compactMap { dictionary in
            guard let conversationId = dictionary["id"] as? String,
                  let name = dictionary["name"] as? String,
                  let otherUserEmail = dictionary["other_user_email"] as? String,
                  let latestMessage = dictionary["latest_message"] as? [String: Any],
                  let date = latestMessage["date"] as? String,
                  let message = latestMessage["message"] as? String,
                  let isRead = latestMessage["is_read"] as? Bool else {
                      return nil
                  }
            
            let latestMessageObject = LatestMessage(date: date,
                                                    text: message,
                                                    isRead: isRead)
            return Conversation(id: conversationId,
                                name: name,
                                otherUserEmail: otherUserEmail,
                                latestMessage: latestMessageObject)
        }
        completion(.success(conversations))
    })
}
检查过期聊天函数
public func listenForMessages(id: String, completion: @escaping (Bool, String, Date) -> Void) {
    DatabaseManager.shared.getAllMessagesForConversation(with: id, completion: { [weak self] result in
        guard let _ = self else { return }
        switch result {
        case .success(let messages):
            print("成功获取消息:\(messages)")
            guard !messages.isEmpty else {
                print("消息为空")
                return
            }
            print(messages)
            guard let date = messages.first?.sentDate else {
                return
            }
            let tempCalendar = Calendar.current
            let oneHourAfter = tempCalendar.date(byAdding: .hour, value: 1, to: date)
            let (val, isNeedToDelete) = CommonClass().getDiffrenceBetweenDates(date: oneHourAfter!.timeIntervalSince1970)
            print("============剩余时间数据库============", oneHourAfter)
            print("============剩余日期数据库============", val)
            if isNeedToDelete {
                DispatchQueue.global(qos: .background).async {
                    self?.deleteOldChats(id: id, completion: { isDeleted in
                        print(isDeleted)
                        completion(true, String(), date)
                    })
                }
            } else {
                completion(false, val, oneHourAfter ?? Date())
            }
        case .failure(let error):
            print("获取消息失败:\(error)")
        }
    })
}
删除消息函数
private func deleteOldChats(id: String, completion: @escaping (Bool) -> Void) {
    DatabaseManager.shared.deleteConversation(conversationId: id, completion: { [weak self] success in
        guard let strongSelf = self else { return }
        if success {
            print("删除成功")
            completion(true)
        } else {
            print("无法删除")
            completion(false)
        }
    })
}
根据我的理解,Firebase使用套接字,每当执行CRUD操作时,这些套接字会更新,这可能是问题的原因。
我希望能够停止每次重新加载数据并且数据需要正确删除,而不影响主线程。
英文:
I have two functions here one for listing all chat created by user and one for delete chat after sometime. so, when i tried to load user all chat it will check chat time is ended than it will deleted while loading. when i go for users chat it will perform all things which i mentioned and what i get page getting reload every 0.5 seconds.
Fetch Messages Function
///Fetches and returns all the conversations for the user with passed in email
    public func getAllConversations(for email:String, completion: @escaping(Result<[Conversation], Error>)->Void){
        database.child("\(email)/conversations").observe(.value, with: {snapshot in
            guard let value = snapshot.value as? [[String: Any]] else{
                completion(.failure(DatabaseError.failedToFetch))
                return
            }
            let conversations: [Conversation] = value.compactMap { dictionary in
                guard let conversationId = dictionary["id"] as? String,
                      let name = dictionary["name"] as? String,
                      let otherUserEmail = dictionary["other_user_email"] as? String,
                      let latestMessage = dictionary["latest_message"] as? [String:Any],
                      let date = latestMessage["date"] as? String,
                      let message = latestMessage["message"] as? String,
                      let isRead = latestMessage["is_read"] as? Bool else{
                          return nil
                      }
                
                let latestMessageObject = LatestMessage(date: date,
                                                        text: message,
                                                        isRead: isRead)
                return Conversation(id: conversationId,
                                    name: name,
                                    otherUserEmail: otherUserEmail,
                                    latestMessage: latestMessageObject)
            }
            completion(.success(conversations))
        })
    }
Checking For Expiration Chat
public func listenForMessages(id:String, completion: @escaping (Bool, String, Date) -> Void) {
        DatabaseManager.shared.getAllMessagesForConversation(with: id, completion: { [weak self] result in
            guard let _ = self else {return}
            switch result {
            case .success(let messages):
                print("success in getting messages:\(messages)")
                guard !messages.isEmpty else{
                    print("messages are empty")
                    return
                }
                print(messages)
                guard let date = messages.first?.sentDate else {
                    return
                }
                let tempCalendar = Calendar.current
                let oneHourAfter = tempCalendar.date(byAdding: .hour, value: 1, to: date)
                let (val,isNeedToDelete) = CommonClass().getDiffrenceBetweenDates(date: oneHourAfter!.timeIntervalSince1970)
                print("============REMAIN TIME DB============",oneHourAfter)
                print("============REMAIN DATE DB============",val)
                if isNeedToDelete {
                    DispatchQueue.global(qos: .background).async {
                        self?.deleteOldChats(id: id, completion: { isDeleted in
                            print(isDeleted)
                            completion(true,String(),date)
                        })
                    }
                }else {
                    completion(false,val,oneHourAfter ?? Date())
                }
            case .failure(let error):
                print("failed to get messages:\(error)")
            }
        })
    }
Delete Messages Function
private func deleteOldChats(id:String, completion: @escaping (Bool) -> Void) {
    DatabaseManager.shared.deleteConversation(conversationId: id, completion: { [weak self] success in
        guard let strongSelf = self else {return}
        if success{
            print("Deleted Succesfully")
            completion(true)
        }else {
            print("Not able to delete")
            completion(false)
        }
    })
}
As per my understanding firebase use sockets and those are updated whenever we perform CRUD Operation that is the issue over here.
i want to stop reload data every time and data needs to be deleted properly without affecting main thread.
答案1
得分: 0
我在Firebase的文档中找到了简单的答案。
我在我的代码中对database进行了更改:
database.child("\(email)/conversations").observe(.value)
改为
database.child("\(email)/conversations").observeSingleEvent(of: .value)
英文:
Thanks To @FrankvanPuffelen
i found easy answer on firebase document.
i made changes on database in my code
database.child("\(email)/conversations").observe(.value)
to
database.child("\(email)/conversations").observeSingleEvent(of: .value)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论