gpt4 book ai didi

ios - 在Swift中使用Firebase计数看不见的邮件

转载 作者:行者123 更新时间:2023-12-01 19:44:53 28 4
gpt4 key购买 nike

我正在尝试编写聊天应用程序。

我想计算未查看(看不见)的邮件数量。

我的数据库如下所示:

user-messages
|
|_messages
|
|_UserID1
| |
| |_UserID2
| |
| |_ MessageID1
| |_ MessageID2
| |_ MessageID3
| |_ etc...
|
|_UserID2
| |
| |_UserID1
| |
| |_ MessageID1
| |_ MessageID2
| |_ MessageID3
| |_ etc...

对于Messages对象:
messages
|
|_messageID1
| |
| |_ notViewed: false / true
| |_ text: "Message text"
| |_ timestamp: 1522230692
| |_ etc...
|
|_messageID2
| |
| |_ notViewed: false / true
| |_ text: "Message text"
| |_ timestamp: 1522230692
| |_ etc...

我到达以获得链接到特定用户的所有消息ID:
var REF_MESSAGE = Database.database().reference().child("messages")
var REF_USER_MESSAGE = Database.database().reference().child("user-messages").child("messages")


func fetchUnviewedMessages(withId id: String, completion: @escaping (Int) -> Void ) {

REF_USER_MESSAGE.child(id).observe(.childAdded) { (snapshot) in

let userId = snapshot.key as String

self.REF_USER_MESSAGE.child(id).child(userId).observe(.childAdded, with: { (snapshot) in
let messageId = snapshot.key

// This part is where I have a problem
self.fetchMessageNotViewed(messageId, completion: { (nbMessageNotRead) in
completion(nbMessageNotRead)
})
})
}
}

但我不知道该如何处理该列表,以观察未见消息的数量...

我尝试过,但是没有成功:
func fetchMessageNotViewed(_ messageId: String, completion: @escaping (Int) -> Void) {
guard let currentUid = Api.User.CURRENT_USER?.uid else {
return
}

REF_MESSAGE.child(messageId).queryOrdered(byChild: "notViewed").queryEqual(toValue: true).observe(.value, with: { (snapshot) in

let count = Int(snapshot.childrenCount)
print(count)
}, withCancel: nil)
}

最佳答案

我们可以利用复合值来相当轻松地处理此问题。

对Firebase结构消息节点进行简单的更改:

messages
|
|_messageID1
| |
| |_ notViewed: false / true
| |_ text: "Message text"
| |_ timestamp: 1522230692
| |_ forUid_status: "UserId1_unread" //<- Compound value
| |_ etc...
|
|_messageID2
| |
| |_ notViewed: false / true
| |_ text: "Message text"
| |_ timestamp: 1522230692
| |_ forUid_status: "UserId1_read" //<- Compound value
| |_ etc...

那么一个简单的查询就会显示出UserId1未读消息的数量
let messagesRef = self.ref.child("messages")
let uid = "UserId1"
let status = "unread"
let queryString = uid + "_" + status //results in a string UserId1_unread

let ref = messagesRef.queryOrdered(byChild: "forUid_status").queryEqual(toValue: queryString)
ref.observe(.value, with: { snapshot in
if snapshot.exists() {
let count = snapshot.childrenCount
print("unread messages: \(count)")
} else {
print("no unread messages")
}
})

针对上述Firebase运行此代码会导致
unread messages: 1

这也可能有助于加载未读消息,因为不仅可以获取未读消息的计数,而且将观察者添加到该节点还可以在为UserId1添加新的未读消息时通知应用程序

关于ios - 在Swift中使用Firebase计数看不见的邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49531960/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com