【发布时间】:2017-05-19 12:21:34
【问题描述】:
我正在创建一个聊天应用程序,并且我在表格视图单元格中列出了两个用户之间发送的所有消息。例如,我在两个用户之间总共有四个文本,所以我有四个单元格。但是,我想对单元格进行分组,以便我只有一个单元格,因为我的 loggedInUser 只与一个人交流。无论我做什么,消息都不会附加。
func loadData(){
if (FIRAuth.auth()?.currentUser) != nil{
FIRDatabase.database().reference().child("messages").observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in
let loggedInUserData = snapshot
if let postsDictionary = snapshot .value as? [String: AnyObject] {
for post in postsDictionary {
let messages = post.value as! [String: AnyObject]
for (id, value) in messages {
let info = value as! [String: AnyObject]
if let receiver = info["ReceiverId"] {
print("\(id): \(receiver)")
self.messages.Array(value)
}
}
self.MessageTableView.reloadData()
}
}})}
}
我认为问题出在self.messages.Array(value) 我只需要在相同的两个用户之间附加消息,但我找不到正确的代码
这是我的单元格的样子:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell", for: indexPath) as! MessageTableViewCell
//Configure the cell
print(messages[indexPath.row])
let message = self.messages[indexPath.row] as! [String: AnyObject]
if let seconds = message["timestamp"] as? Double {
let timeStampDate = NSDate(timeIntervalSince1970: seconds)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
cell.Time.text = dateFormatter.string(from: timeStampDate as Date)
}
cell.Message.text = message["text"] as? String
// cell.SellerName.text = message["ReceiverId"] as? String
if let imageName = message["ReceiverId"] as? String {
let ref = FIRDatabase.database().reference().child("posts").child(imageName)
ref.observeSingleEvent(of: .value, with: { (snapshot)
in
if let dictionary = snapshot.value as? [String: AnyObject]{
for post in dictionary {
let messages = post.value as! [String: AnyObject]
for (id, value) in messages {
cell.SellerName.text = messages["username"] as? String
if (messages["uid"] as? String) != nil {
let uidPoster = messages["uid"] as? String
let imageRef = FIRStorage.storage().reference().child((uidPoster)!+"/profile_pic.jpg")
imageRef.data(withMaxSize: 25 * 1024 * 1024, completion: { (data, error) -> Void in
if error == nil {
let image = UIImage(data: data!)
cell.UserPic.image = image
cell.UserPic.layer.cornerRadius = 30
cell.UserPic.clipsToBounds = true
}else {
print("Error downloading image:" )
}})}
self.messages.add(value)
}
}
}
})
}
return cell
}
我的 firebase 消息路径是:
FIRDatabase.database().reference().child("messages").child("(self.convoId!)").childByAutoId()
【问题讨论】:
-
离题但为什么你会观察一个事件而不是添加孩子?这样所有旧邮件和新邮件都会被下载。
-
@J.Doe 它工作正常。下载新旧消息没有问题
-
请解释一下。你想当我按顺序发送 4 条消息时,它们应该彼此附加为一个单元格吗?
-
就像手机中的短信一样,当您给某人发短信时,您的所有聊天都应该在一个单元格中@VladPulichev
-
@juelizabeth 其实我没看懂你的意思:(请加截图,什么意思?
标签: ios arrays swift firebase firebase-realtime-database