Skip to content

Instantly share code, notes, and snippets.

extension Notification.Name {
static let userDidLogin = Notification.Name(rawValue: "userDidLogin")
static let userDidLogout = Notification.Name(rawValue: "userDidLogout")
}
func send(_ message: Message) {
guard let data = try? JSONEncoder().encode(message) else {
// Handle error
return
}
webSocket?.write(data: data)
add(message, direction: .sent)
}
extension MessagingViewController: MessagingDataSourceDelegate {
func dataSourceDidUpdate() {
tableView.reloadData()
scrollToLastMessage()
}
private func scrollToLastMessage() {
let rowCount = tableView.numberOfRows(inSection: 0)
if rowCount > 1 {
extension MessagingDataSource: DataStoreDelegate {
func dataStoreDidReceiveNewMessage(forConversationWith user: UserID) {
delegate?.dataSourceDidUpdate()
}
}
private func add(_ message: Message, direction: Message.CommunicationDirection) {
let conversationId = conversationIdFor(message: message, direction: direction)
if let existingConverstion = conversations[conversationId] {
existingConverstion.append(message)
} else {
let newConversation = Conversation(user: conversationId)
newConversation.append(message)
conversations[conversationId] = newConversation
}
delegate?.dataStoreDidReceiveNewMessage(forConversationWith: conversationId)
extension MessageDataStore: WebSocketDelegate {
func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
if let message = try? JSONDecoder().decode(Message.self, from: data) {
add(message, direction: .received)
}
}
// ...
// Other delegate method implementations
private func connectWebSocket() {
let url = URL(string: "ws://localhost:8080/api/echo")!
var urlRequest = URLRequest(url: url)
guard let tokens = LoginSessionManager.shared.tokens else {
// Handle connection failure
return
}
urlRequest.setValue("Bearer \(tokens.access_token)", forHTTPHeaderField: "Authorization")
webSocket = WebSocket(request: urlRequest)
webSocket?.delegate = self
class MessageDataStore: DataStore {
/// A singleton object.
static let shared = MessageDataStore()
/// The web socket for network communication.
private var webSocket: WebSocketClient?
/// The delegate is informed whenever new messages arrive.
weak var delegate: DataStoreDelegate?
func send(_ message: String) {
let newMessage = Message(text: message, receiverId: userId)
dataStore.send(newMessage)
}
extension MessagingDataSource: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let message = messages[indexPath.row]
let identifier = cellIdentifier(for: message)
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! MessageCell