Firebase聊天获取和删除特定聊天调用Firebase实时套接字持续不断

huangapple go评论81阅读模式
英文:

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&lt;[Conversation], Error&gt;)-&gt;Void){
        database.child(&quot;\(email)/conversations&quot;).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[&quot;id&quot;] as? String,
                      let name = dictionary[&quot;name&quot;] as? String,
                      let otherUserEmail = dictionary[&quot;other_user_email&quot;] as? String,
                      let latestMessage = dictionary[&quot;latest_message&quot;] as? [String:Any],
                      let date = latestMessage[&quot;date&quot;] as? String,
                      let message = latestMessage[&quot;message&quot;] as? String,
                      let isRead = latestMessage[&quot;is_read&quot;] 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) -&gt; Void) {
        DatabaseManager.shared.getAllMessagesForConversation(with: id, completion: { [weak self] result in
            guard let _ = self else {return}
            switch result {
            case .success(let messages):
                print(&quot;success in getting messages:\(messages)&quot;)
                guard !messages.isEmpty else{
                    print(&quot;messages are empty&quot;)
                    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(&quot;============REMAIN TIME DB============&quot;,oneHourAfter)
                print(&quot;============REMAIN DATE DB============&quot;,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(&quot;failed to get messages:\(error)&quot;)
            }
        })
    }

Delete Messages Function

private func deleteOldChats(id:String, completion: @escaping (Bool) -&gt; Void) {
    DatabaseManager.shared.deleteConversation(conversationId: id, completion: { [weak self] success in
        guard let strongSelf = self else {return}
        if success{
            print(&quot;Deleted Succesfully&quot;)
            completion(true)
        }else {
            print(&quot;Not able to delete&quot;)
            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

感谢@FrankvanPuffelen

我在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(&quot;\(email)/conversations&quot;).observe(.value)

to

database.child(&quot;\(email)/conversations&quot;).observeSingleEvent(of: .value)

huangapple
  • 本文由 发表于 2023年5月10日 13:31:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76215176.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定