У меня есть групповой мессенджер, и я стараюсь постоянно обновлять изображение и имя пользователя, если они решили изменить изображение своего профиля или обновить свое имя. Проблема в том, что при заполнении ячеек данные не совпадают. Так что все загружается, изображение и имя, но загружаются не те люди.
Вызов и настройка всех пользователей (клиентов, сотрудников и предприятий)
Это настройка пользователей для структуры данных
func getCustomerData() {
Database.database().reference().child("user_profiles").observe(.childAdded, with: { snapshot in
self.customerData.append(CustomerData(snapshot: snapshot))
print(snapshot)
print("Printed Customer Data")
})
}
func getEmployeeData() {
Database.database().reference().child("employees").observe(.childAdded, with: { snapshot in
self.employeeData.append(EmployeeData(snapshot: snapshot))
print(snapshot)
print("Printed Employee Data")
})
}
func getBusinessData() {
Database.database().reference().child("Businesses").observe(.childAdded, with: { snapshot in
self.businessData.append(BusinessData(snapshot: snapshot))
print(snapshot)
print("Printed Business Data")
})
}
Структура данных для клиентов, сотрудников и бизнеса. Одинаковый тип конструкции для всех 3
import UIKit
import Firebase
class CustomerData: NSObject {
var customerName: String?
var customerPicture: String?
var customerUID: String?
init(snapshot: DataSnapshot) {
if let dictionary = snapshot.value as? [String: AnyObject] {
customerName = dictionary["name"] as? String
customerUID = dictionary["uid"] as? String
customerPicture = dictionary["profPicString"] as? String
}
}
}
Настройка ячейки
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ChatMessageCell
cell.chatLogController = self
let customer = customerData[indexPath.item]
let employee = employeeData[indexPath.item]
let business = businessData[indexPath.item]
let message = messages[indexPath.row]
cell.message = message
cell.customer = customer
cell.employee = employee
cell.business = business
setupChatMessageCell(cell,message,customer,employee,business)
if let text = message.text {
cell.textView.text = text
cell.bubbleWidthAnchor?.constant = estimateSizeOfText(text).width + 32
cell.textView.isHidden = false
} else if message.imageUrl != nil {
cell.bubbleWidthAnchor?.constant = 200
cell.textView.isHidden = true
}
cell.playButton.isHidden = message.videoUrl == nil
return cell
}
private func setupChatMessageCell(_ cell: ChatMessageCell, _ message: GroupMessage, _ customer: CustomerData, _ employee: EmployeeData, _ business: BusinessData) {
if message.fromId == Auth.auth().currentUser?.uid {
//outgoing messages
cell.bubbleView.backgroundColor = ChatMessageCell.blueColor
cell.textView.textColor = .white
cell.bubbleLeftAnchor?.isActive = false
cell.bubbleRightAnchor?.isActive = true
cell.profileImageView.isHidden = true
cell.nameLabel.textColor = .gray
cell.nameRightAnchor?.isActive = true
cell.nameLeftAnchor?.isActive = false
cell.nameLabel.text = customer.customerName?.description
//cell.nameLabel.text = message.customerName
} else if message.fromId == business.businessUID?.description {
//incoming messagese
let customerImage = business.businessPicture?.description
cell.profileImageView.loadImageUsingCacheWithUrlString(customerImage!)
cell.profileImageView.isHidden = false
cell.bubbleView.backgroundColor = UIColor(red: 240, green: 240, blue: 240)
cell.textView.textColor = .black
cell.bubbleLeftAnchor?.isActive = true
cell.bubbleRightAnchor?.isActive = false
cell.profileImageView.isHidden = false
cell.nameRightAnchor?.isActive = false
cell.nameLeftAnchor?.isActive = true
cell.nameLabel.textColor = .black
cell.nameLabel.text = business.businessName
} else {
let customerImage = employee.employeePicture?.description
cell.profileImageView.loadImageUsingCacheWithUrlString(customerImage!)
cell.profileImageView.isHidden = false
cell.bubbleView.backgroundColor = UIColor(red: 240, green: 240, blue: 240)
cell.textView.textColor = .black
cell.bubbleLeftAnchor?.isActive = true
cell.bubbleRightAnchor?.isActive = false
cell.profileImageView.isHidden = false
cell.nameRightAnchor?.isActive = false
cell.nameLeftAnchor?.isActive = true
cell.nameLabel.textColor = .black
cell.nameLabel.text = employee.employeeName
}
if let imageUrl = message.imageUrl {
cell.messageImageView.loadImageUsingCacheWithUrlString(imageUrl)
cell.messageImageView.isHidden = false
cell.bubbleView.backgroundColor = .clear
} else {
cell.messageImageView.isHidden = true
}
}
Структура сообщений группы Firebase
Мне нужна помощь о том, как сопоставить сообщение «fromId» нужному пользователю. У меня есть 3 разных профиля, клиентов, сотрудников и предприятий. На данный момент установлены неправильные данные для сообщений о бизнесе и сотрудниках. Данные для клиента верны, что является первым утверждением «если еще».
Как загружаются данные
Так что, как видите, отображаемое имя и изображение профиля отличаются от имени внутри сообщения.