-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChatLogView.swift
315 lines (245 loc) · 8.35 KB
/
ChatLogView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
//
// ChatLogView.swift
// Project CV
//
// Created by Tran Duc Duy on 31/03/2022.
//
import SwiftUI
import Firebase
class ChatLogViewModel: ObservableObject{
@Published var chatText = ""
@Published var errorMessage = ""
@Published var chatMessage = [ChatMessage]()
var chatUser: ChatUser?
init(chatUser:ChatUser?){
self.chatUser = chatUser
fetchMessage()
}
var firestoreListener: ListenerRegistration?
func fetchMessage() {
guard let fromId = FirebaseManager.shared.auth.currentUser?.uid
else{return}
guard let toId = chatUser?.uid else{return}
firestoreListener?.remove()
chatMessage.removeAll()
firestoreListener = FirebaseManager.shared.firestore.collection(FirebaseConstants.messages)
.document(fromId)
.collection(toId)
.order(by: FirebaseConstants.timestamp)
.addSnapshotListener { querySnapshot, error in
if let error = error {
self.errorMessage = "Failed to listen for message :\(error)"
print(error)
return
}
querySnapshot?.documentChanges.forEach({ change in
if change.type == .added{
do{
let cm = try change.document.data(as: ChatMessage.self)
self.chatMessage.append(cm)
print("Appen ChatMessage in chatLogView:\(Date())")
}
catch{
print("Failed to decode message:\(error)")
}
}
})
DispatchQueue.main.async {
self.count += 1
}
}
}
func handelSend(){
print(chatText)
guard let fromId = FirebaseManager.shared.auth.currentUser?.uid
else{
return
}
guard let toId = chatUser?.uid
else{
return
}
//create a new collection called "messages" in firestore
//sender
let document = FirebaseManager.shared.firestore.collection(FirebaseConstants.messages)
.document(fromId)
.collection(toId)
.document()
let messageData = ChatMessage(id: nil, fromId: fromId, toId: toId, text: chatText, timestamp: Date())
try? document.setData(from:messageData){error in
if let error = error {
self.errorMessage = "Failed to save messages into firestore\(error)"
return
}
print("Successfully saved to current sending messages")
self.persistRecentMessage()
self.chatText = " "
self.count += 1
}
//recipient
let recipientMessage = FirebaseManager.shared.firestore.collection("messages")
.document(toId)
.collection(fromId)
.document()
try? recipientMessage.setData(from:messageData){error in
if let error = error {
self.errorMessage = "Failed to save messages into firestore\(error)"
return
}
print("Recipient saved message as well")
}
}
private func persistRecentMessage(){
guard let chatUser = chatUser else {
return
}
guard let uid = FirebaseManager.shared.auth.currentUser?.uid else {return}
guard let toId = self.chatUser?.uid else {return}
let document=FirebaseManager.shared.firestore.collection("recent message")
.document(uid)
.collection("messages")
.document(toId)
let data = [
FirebaseConstants.timestamp:Timestamp(),
FirebaseConstants.text:self.chatText,
FirebaseConstants.toId: uid,
FirebaseConstants.fromId:toId,
FirebaseConstants.imageProfile: chatUser.imageProfile ,
FirebaseConstants.email: chatUser.email
] as [String : Any]
document.setData(data) { error in
if let error = error{
self.errorMessage = "Failed to save recent messager\(error)"
print("Failed to save recent messager\(error)")
return
}
}
}
@Published var count = 0
}
struct ChatLogView:View{
// init(chatUser:ChatUser?){
// self.chatUser = chatUser
// self.mm = .init(chatUser: chatUser)
//}
//let chatUser:ChatUser?
@ObservedObject var mm: ChatLogViewModel
var body: some View{
ZStack{
messageView
Text(mm.errorMessage)
VStack{
Spacer()
chatBottomBar
.background(Color.white)
}
}
.navigationTitle(mm.chatUser?.email ?? "")
.navigationBarTitleDisplayMode(.inline)
.onDisappear{
mm.firestoreListener?.remove()
}
}
static let emptyScrollString = "Empty"
private var messageView: some View{
ScrollView{
ScrollViewReader{ scrollViewProxy in
VStack{
ForEach(mm.chatMessage){
message in
MessageView(message: message)
}
HStack{ Spacer() }
.id(Self.emptyScrollString)
}
.onReceive(mm.$count) {_ in
withAnimation(.easeOut(duration: 0.5)){
scrollViewProxy.scrollTo(Self.emptyScrollString, anchor:.bottom)
}
}
}
}
.background(Color(.init(white: 0.92, alpha: 1)))
.safeAreaInset(edge: .bottom){
chatBottomBar
.background(Color(.systemBackground).ignoresSafeArea())
}
}
private var chatBottomBar:some View{
HStack(spacing:16){
Image(systemName:"photo.on.rectangle")
.font(.system(size: 23))
.foregroundColor(Color(.darkGray))
ZStack{
Description()
TextEditor(text: $mm.chatText)
.opacity(mm.chatText.isEmpty ? 0.5: 1 )
}
.frame(height: 40)
Button {
mm.handelSend()
} label: {
Text("Send")
.foregroundColor(.white)
}
.padding(.vertical,8)
.padding(.horizontal)
.background(Color.blue)
.cornerRadius(4)
}
.padding(.horizontal)
.padding(.vertical,8)
}
}
private struct Description: View {
var body: some View {
HStack {
Text("Description")
.foregroundColor(Color(.gray))
.font(.system(size: 17))
.padding(.leading, 5)
.padding(.top, -4)
Spacer()
}
}
}
struct MessageView:View{
let message: ChatMessage
var body: some View{
VStack{
if message.fromId == FirebaseManager.shared.auth.currentUser?.uid{
HStack{
Spacer()
HStack{
Text(message.text)
.foregroundColor(.white)
}
.padding()
.background(Color.blue)
.cornerRadius(8)
}
}else{
HStack{
HStack{
Text(message.text)
.foregroundColor(.black)
}
.padding()
.background(Color.white)
.cornerRadius(8)
Spacer()
}
}
}
.padding(.horizontal)
.padding(.top,8)
}
}
struct ChatLogView_Previews: PreviewProvider {
static var previews: some View {
/*NavigationView{
ChatLogView(chatUser: .init(data: ["uid":"tràndsjfndsvl","email":"[email protected]"]))
}*/
MainMessagesView()
}
}