Когда пользователь создает сообщение с такой информацией, как заголовок, местоположение, описание и т. Д. c., Я хочу автоматически создать чат с учетной записью администратора (уникальный UID Firebase). Я хочу, чтобы первым сообщением этого чата была информация из указанного выше сообщения. Мне удалось сохранить чат с информацией, но у меня нет возможности восстановить ее. Каждое сообщение пользователя будет отображаться в домашнем представлении пользователя как UITableView, каждая ячейка которого ведет к отдельному чату с администратором. Я следую этому руководству .
class FinalVC: UIViewController {
func addPost(value: String, imagesData: [Data]) {
guard let uid = Auth.auth().currentUser?.uid else { return }
let userPostRef = Database.database().reference().child("posts").child(uid)
let ref = userPostRef.childByAutoId()
let values = ["value": valueFinal, "findersFee": findersFee, "itemTitle": titleOfItem, "itemDescription": descriptionField, "confirmed": isConfirmed, "location": location, "bePresent": shouldBePresent, "verification": "test", "category": categoryTitle, "creationDate": Date().timeIntervalSince1970] as [String : Any]
let users = [self.currentUser.uid, self.user2UID]
let data = values
let db = Firestore.firestore().collection("Chats")
db.addDocument(data: data) { (error) in
if let error = error {
print("Unable to create chat! \(error)")
return
} else {
// self.loadChat()
}
}
ref.updateChildValues(values) { (err, ref) in
if let err = err {
print("Failed to save post to DB", err)
return
}
print("Successfully saved post to DB")
// self.dismiss(animated: true, completion: nil)
}
}
class ChatViewController: MessagesViewController, InputBarAccessoryViewDelegate, MessagesDataSource, MessagesLayoutDelegate, MessagesDisplayDelegate {
var currentUser: User = Auth.auth().currentUser!
var user2Name: String?
var user2ImgUrl: String?
var user2UID = "CVKuU1WWo2ScavfrjH4h3HWDSCv1"
func createNewChat() {
let users = [self.currentUser.uid, self.user2UID]
let data: [String: Any] = [
"users":users
]
let db = Firestore.firestore().collection("Chats")
db.addDocument(data: data) { (error) in
if let error = error {
print("Unable to create chat! \(error)")
return
} else {
self.loadChat()
}
}
}
func loadChat() {
//Fetch all the chats which has current user in it
let db = Firestore.firestore().collection("Chats")
.whereField("users", arrayContains: Auth.auth().currentUser?.uid ?? "Not Found User 1")
db.getDocuments { (chatQuerySnap, error) in
if let error = error {
print("Error: \(error)")
return
} else {
//Count the no. of documents returned
guard let queryCount = chatQuerySnap?.documents.count else {
return
}
if queryCount == 0 {
//If documents count is zero that means there is no chat available and we need to create a new instance
self.createNewChat()
}
else if queryCount >= 1 {
//Chat(s) found for currentUser
for doc in chatQuerySnap!.documents {
let chat = Chat(dictionary: doc.data())
//Get the chat which has user2 id
if (chat?.users.contains(self.user2UID))! {
self.docReference = doc.reference
//fetch it's thread collection
doc.reference.collection("thread")
.order(by: "created", descending: false)
.addSnapshotListener(includeMetadataChanges: true, listener: { (threadQuery, error) in
if let error = error {
print("Error: \(error)")
return
} else {
self.messages.removeAll()
for message in threadQuery!.documents {
let msg = Message(dictionary: message.data())
self.messages.append(msg!)
print("Data: \(msg?.content ?? "No message found")")
}
self.messagesCollectionView.reloadData()
self.messagesCollectionView.scrollToBottom(animated: true)
}
})
return
} //end of if
} //end of for
self.createNewChat()
} else {
print("Let's hope this error never prints!")
}
}
}
}
private func insertNewMessage(_ message: Message) {
messages.append(message)
messagesCollectionView.reloadData()
DispatchQueue.main.async {
self.messagesCollectionView.scrollToBottom(animated: true)
}
}
private func save(_ message: Message) {
let data: [String: Any] = [
"content": message.content,
"created": message.created,
"id": message.id,
"senderID": message.senderID,
"senderName": message.senderName
]
docReference?.collection("thread").addDocument(data: data, completion: { (error) in
if let error = error {
print("Error Sending message: \(error)")
return
}
self.messagesCollectionView.scrollToBottom()
})
}
// MARK: - InputBarAccessoryViewDelegate
func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
let message = Message(id: UUID().uuidString, content: text, created: Timestamp(), senderID: currentUser.uid, senderName: currentUser.uid)
//messages.append(message)
insertNewMessage(message)
save(message)
inputBar.inputTextView.text = ""
messagesCollectionView.reloadData()
messagesCollectionView.scrollToBottom(animated: true)
}
// MARK: - MessagesDataSource
func currentSender() -> SenderType {
return Sender(id: Auth.auth().currentUser!.uid, displayName: Auth.auth().currentUser?.displayName ?? "Name not found")
}