-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathChatViewController.swift
More file actions
232 lines (173 loc) · 7.94 KB
/
ChatViewController.swift
File metadata and controls
232 lines (173 loc) · 7.94 KB
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
//
// ChatViewController.swift
// VideoSDKRTC_Example
//
// Created by Parth Asodariya on 27/01/23.
//
import UIKit
import MessageKit
import VideoSDKRTC
import InputBarAccessoryView
class ChatViewController: MessagesViewController {
// MARK: - Properties
/// Meeting Reference
public var meeting: Meeting
/// Chat Topic
public var topic: String
/// Message List
private var messages: [Message] = []
// Time Formatter
private let timeFormatter: DateFormatter = {
var formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
return formatter
}()
// MARK: - Init
init(meeting: Meeting, topic: String) {
self.meeting = meeting
self.topic = topic
let pubsubMessages = meeting.pubsub.getMessagesForTopic(topic)
messages = pubsubMessages.map({ Message(pubsubMessage: $0) })
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
configureMessageCollectionView()
configureMessageInputBar()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
reloadAndScrollToLast()
}
// MARK: - Public
func showNewMessage(_ pubsubMessage: PubSubMessage) {
let message = Message(pubsubMessage: pubsubMessage)
messages.append(message)
// Reload last section to update header/footer labels and insert a new one
messagesCollectionView.performBatchUpdates({
messagesCollectionView.insertSections([messages.count - 1])
if messages.count >= 2 {
messagesCollectionView.reloadSections([messages.count - 2])
}
}, completion: { [weak self] _ in
if self?.isLastSectionVisible() == true {
self?.messagesCollectionView.scrollToLastItem(animated: true)
}
})
}
}
// MARK: - Helpers
extension ChatViewController {
// relod and scroll to last message
func reloadAndScrollToLast() {
messagesCollectionView.reloadData()
messagesCollectionView.scrollToLastItem()
}
// checks if last section is visible
func isLastSectionVisible() -> Bool {
guard !messages.isEmpty else { return false }
let lastIndexPath = IndexPath(item: 0, section: messages.count - 1)
return messagesCollectionView.indexPathsForVisibleItems.contains(lastIndexPath)
}
}
// MARK: - MessagesDataSource
extension ChatViewController: MessagesDataSource {
func currentSender() -> SenderType {
ChatUser(senderId: meeting.localParticipant.id, displayName: meeting.localParticipant.displayName)
}
func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int {
messages.count
}
func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType {
messages[indexPath.section]
}
}
// MARK: - MessagesDisplayDelegate, MessagesLayoutDelegate
extension ChatViewController: MessagesDisplayDelegate, MessagesLayoutDelegate {
func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
let name = message.sender.senderId == meeting.localParticipant.id ? "You" : message.sender.displayName
return NSAttributedString(
string: name,
attributes: [.foregroundColor: UIColor.lightGray, .font: UIFont.systemFont(ofSize: 15)])
}
func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
return 25
}
func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
return NSAttributedString(
string: timeFormatter.string(from: message.sentDate),
attributes: [.foregroundColor: UIColor.lightGray, .font: UIFont.systemFont(ofSize: 15)])
}
func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
return 25
}
func textColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
UIColor.white
}
func backgroundColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
UIColor.systemDarkBackground?.withAlphaComponent(0.4) ?? UIColor(named: "systemDarkBackground")!
}
func messageStyle(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageStyle {
return MessageStyle.bubble
}
}
// MARK: - MessageInputBarDelegate
extension ChatViewController: InputBarAccessoryViewDelegate {
func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
// send (publish) message
Task {
do {
try await meeting.pubsub.publish(topic: topic, message: text, options: ["persist": true])
} catch {
print("Error while sending message: \(error)")
}
}
// reset textView
messageInputBar.inputTextView.text = String()
messageInputBar.invalidatePlugins()
}
}
// MARK: - Setup
extension ChatViewController {
func setupNavigationBar() {
edgesForExtendedLayout = []
self.navigationItem.title = topic
self.setNavigationBarAppearance(self.navigationController!.navigationBar)
}
func configureMessageCollectionView() {
messagesCollectionView.backgroundColor = UIColor(named: "chatBackgroundColor")!
messagesCollectionView.messagesDataSource = self
messagesCollectionView.messagesDisplayDelegate = self
messagesCollectionView.messagesLayoutDelegate = self
// no avatars
let layout = messagesCollectionView.messagesCollectionViewFlowLayout
layout.setMessageIncomingAvatarSize(.zero)
layout.setMessageOutgoingAvatarSize(.zero)
let incomingInsets = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 0)
let outgoingInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 12)
layout.setMessageIncomingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .left, textInsets: incomingInsets))
layout.setMessageIncomingMessageTopLabelAlignment(LabelAlignment(textAlignment: .left, textInsets: incomingInsets))
layout.setMessageOutgoingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .right, textInsets: outgoingInsets))
layout.setMessageOutgoingMessageTopLabelAlignment(LabelAlignment(textAlignment: .right, textInsets: outgoingInsets))
scrollsToLastItemOnKeyboardBeginsEditing = true
maintainPositionOnKeyboardFrameChanged = true
}
func configureMessageInputBar() {
messageInputBar.delegate = self
messageInputBar.backgroundView.backgroundColor = UIColor(named: "chatItemBackgroundColor")
messageInputBar.inputTextView.backgroundColor = UIColor(named: "chatItemBackgroundColor")
// textview
messageInputBar.inputTextView.tintColor = UIColor.white
messageInputBar.inputTextView.textColor = UIColor.white
messageInputBar.inputTextView.isImagePasteEnabled = false
// send button
messageInputBar.sendButton.setTitleColor(UIColor.white, for: .normal)
messageInputBar.sendButton.setTitleColor(UIColor.white.withAlphaComponent(0.4), for: .highlighted)
messageInputBar.sendButton.activityViewColor = UIColor.lightGray
}
}